Using nameof to access member of generic class without knowing the type

Take these two classes:

class NonGenericClass
{
    public string Member { get; set; }
}

class GenericClass<T>
{
    public string Member { get; set; }
}

I can easily do this:

nameof(NonGenericClass.Member)

But I can't do this:

nameof(GenericClass.Member)

I could do this:

nameof(GenericClass<object>.Member)

But I don't want to.

Is there a way to do what I want without having to resort doing it in a way that I don't want to?

Jon Skeet
people
quotationmark

No, there's no way of using nameof for a generic type (or a member of that generic type) without specifying a type argument. I would personally like to be able to specify the open type as you can with typeof, i.e.

// Would be nice, but isn't valid
string name = nameof(GenericClass<>.Member);

... which would allow distinction between different generic types with different arities in the same way (GenericClass<,>, GenericClass<,,> etc) but that just isn't valid at the moment. There's already a feature request for this which has some support, but it certainly won't be in C# 7, and I'd be surprised if it got in before C# 8 at best.

I suggest you just hold your nose and use GenericClass<int>.Member or similar. Any change that makes that break is likely to make far worse problems than this. If you're consistent about the type argument you use, a simple search and replace should fix it.

people

See more on this question at Stackoverflow