Reputation: 3027
I have an inheritance hierarchy like the following:
public abstract class A
{
public string MyProperty {get; set;}
}
public class B : A
{
}
public class C : A
{
}
I then have a method that uses generics:
public void MyMethod<T>() where T : A
{
var str = nameof(T.MyProperty); // this one fails
}
I'm trying to get the name of MyProperty
, but it fails because I'm trying to do this through a type instead of an object. Is there a clever way of getting the property name without having to pass an object?
Upvotes: 0
Views: 1119
Reputation: 143213
Another option wold be to create "dummy" instance of T
:
public void MyMethod<T>() where T : A
{
var t = default(T);
var str = nameof(t.MyProperty);
}
It seems that compiler is smart enough to remove this dummy instance in release configuration.
Upvotes: 0