Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.".

like image 980
Thomas Flinkow Avatar asked Apr 18 '18 11:04

Thomas Flinkow


Video Answer


2 Answers

Have you tried:

typeof(T).FullName;

or

t.GetType().FullName;

Hope it works for you.

like image 189
PachecoDt Avatar answered Oct 16 '22 22:10

PachecoDt


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.

like image 38
Rotem Avatar answered Oct 16 '22 20:10

Rotem