1

C# How to get properties names of generic class using nameof without specifing a type. I have class as follow:

public class Example<T> where T : class
{
    public DateTime CreatedAt { get; set; } = DateTime.Now; 
}

And I want to get "CreateAt" as string using following:

nameof(Example<>.CreatedAt)

but it doesn't work, I need to specify the type:

nameof(Example<int>.CreatedAt)

Although, for checking the type I can use construction:

typeof(BaseEntity<>)

Why it doesn't work with nameof? Why do I need to define the type?

ElConrado
  • 1,477
  • 4
  • 20
  • 46
  • 3
    See https://github.com/dotnet/csharplang/discussions/702, from 2017 – canton7 Mar 25 '22 at 14:09
  • 2
    you need to specify *a* type; it doesn't need to be *the* type; any type (that satisfies the generic constraints, if any) will work fine (and identically) – Marc Gravell Mar 25 '22 at 14:10
  • Ok @canton7 thanks, so it seems that we haven't had developed such a thing yet.. – ElConrado Mar 25 '22 at 14:20
  • @MarcGravell yes, If I understand correctly, will it work as far as we don't change generic constraints? – ElConrado Mar 25 '22 at 14:21
  • 3
    @ElConrado yes, that'll be fine - and it only impacts compile, since `nameof` is erased during compile and literally doesn't exist at runtime - so if the generic constraints do change (unlikely), that will never cause a surprise break at runtime; worst cast is that it fails next time you build, and you need to change to a different dummy type - i.e. instead of `nameof(Example.CreatedAt)` you might use `nameof(Example.CreatedAt)` (because, for example, someone added a `where T : class` constraint) – Marc Gravell Mar 25 '22 at 14:33

0 Answers0