Search code examples
c#genericsinheritancenameof

C# Generics: How to use nameof to get the name of a base class property


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?


Solution

  • nameof(A.MyProperty).

    You constraint T to be an A anyway.