32

I am trying to get the name of a method on a generic interface. I would expect this to work as the type part would be a valid typeof:

//This does not compile
nameof(IGenericInterface<>.Method)

//This would compile
typeof(IGenericInterface<>)

I think this should be valid c#-6.0 or am I missing something or is there a better way to do this. I don't want to use a string for the Method name as if the method is renamed code would break without any build-time errors.

V. S.
  • 1,086
  • 14
  • 14
Jake Rote
  • 2,177
  • 3
  • 16
  • 41

2 Answers2

51

This is expected. According to the documentation, your expression is disallowed, because it refers to an unbound generic type:

Because the argument needs to be an expression syntactically, there are many things disallowed that are not useful to list. The following are worth mentioning that produce errors: predefined types (for example, int or void), nullable types (Point?), array types (Customer[,]), pointer types (Buffer*), qualified alias (A::B), and unbound generic types (Dictionary<,>), preprocessing symbols (DEBUG), and labels (loop:).

You can work around this limitation by supplying a generic parameter:

nameof(IGenericInterface<object>.Method)

Note: I think Microsoft should tweak nameof feature to allow references to methods of unbound generic types.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 4
    Is strange this is expected, and yes i agree they should allow how would one go about raising that to them. – Jake Rote Oct 14 '15 at 16:16
  • 1
    Under the hood, generics are basically expanded to all the types they are used with, right? This is probably a rather minor concern, but using `nameof(IGenericInterface)` in code will then generate the interface `IGenericInterface` which might not otherwise be needed anywhere. It would definitely make more sense if `nameof()` would support unbound generics. – Elte Hupkes Dec 11 '17 at 12:54
  • 2
    FYI: `object` won't work depending on any constraints on that generic parameter – void.pointer Jun 12 '21 at 19:27
  • 1
    Just be aware that passing anything to it, will force the compiler to generate a real class with an object type, so be aware of this drawback – Al Banna Techno logy Oct 21 '22 at 14:55
4

Just use a sample type in order to compile.

string name = nameof(IGenericInterface<int>.Method) // will be Method
M.kazem Akhgary
  • 18,645
  • 8
  • 57
  • 118