Search code examples
c#genericsnameof

C# nameof generic type without specifying type


Assume I have the type

public class A<T> { }

and somewhere in the code I want to throw an exception related to incorrect usage of that type:

throw new InvalidOperationException("Cannot use A<T> like that.");

So far, so good, but I don't want to hardcode the classes name, so I thought I could maybe use

throw new InvalidOperationException($"Cannot use {nameof(A<T>)} like that.");

instead, but in this context I don't know the exact type T. So I thought maybe I could do it with template specialization like in C++:

throw new InvalidOperationException($"Cannot use {nameof(A)} like that.");

or

throw new InvalidOperationException($"Cannot use {nameof(A<>)} like that.");

but those yield

Incorrect number of type parameters.

and

Type argument is missing.


I absolutely don't want to hardcode the classes name for it might change later. How can I get the name of the class, preferably via nameof?

Optimally, what I want to achieve is "Cannot use A<T> like that." or "Cannot use A like that.".


Solution

  • If you don't care about displaying T, you can just use e.g. nameof(A<object>), assuming object complies with the generic type constraints.

    This results in "Cannot use A like that."

    If you want to print exactly A<T>, you could use:

    $"{nameof(A<T>)}<{nameof(T)}>"
    

    But only from within the class, as T does not exist elsewhere.