user246392
user246392

Reputation: 3027

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?

Upvotes: 0

Views: 1119

Answers (2)

Guru Stron
Guru Stron

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

mm8
mm8

Reputation: 169380

nameof(A.MyProperty).

You constraint T to be an A anyway.

Upvotes: 3

Related Questions