Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nameof with generic types

Tags:

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.

like image 869
Jake Rote Avatar asked Oct 14 '15 16:10

Jake Rote


People also ask

Is it possible to inherit from a generic type?

You can't inherit from the generic type parameter. C# generics are very different from C++ templates. Inheriting from the type parameter requires the class to have a completely different representation based on the type parameter, which is not what happens with .

What is generic type?

A generic type is a generic class or interface that is parameterized over types. The following Box class will be modified to demonstrate the concept.

What are generic type constraints?

C# allows you to use constraints to restrict client code to specify certain types while instantiating generic types. It will give a compile-time error if you try to instantiate a generic type using a type that is not allowed by the specified constraints.

How does a generic method differ from a generic type?

From the point of view of reflection, the difference between a generic type and an ordinary type is that a generic type has associated with it a set of type parameters (if it is a generic type definition) or type arguments (if it is a constructed type). A generic method differs from an ordinary method in the same way.


1 Answers

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.

like image 179
Sergey Kalinichenko Avatar answered Nov 10 '22 00:11

Sergey Kalinichenko