Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use nameof with a generic when everything are known compile-time?

Tags:

c#

.net

generics

public void Test<T>()
{
    Console.WriteLine(nameof(T));
}

Test<int>();

This code literally prints T and not int, which is not useful at all. I would like to get the name of an actual generic type parameter used without using reflections (typeof and then operate on the Type variable, etc.)

I read that the point of generic is to make a variation of code with different type in their definition all ready at compile time. And nameof is also a compile-time operator. In this case it should be enough to know that T here is an int. There must be some way to do this other than having to do it from the user side (e.g. Test<int>(nameof(int)))

If anyone curious about the use case, besides debugging for example I would like to add things to dictionary using the item's class name as a key. This dictionary has exactly one of each shape.

public AddShape<T>(T shape) where T : Shape
{
    dict.Add(nameof(T), shape.SerializableShape);
}
like image 633
5argon Avatar asked Mar 07 '23 18:03

5argon


2 Answers

The nameof construct is for determining the name of a type, variable, field, etc. at compile time. It doesn’t help you when you want a type at runtime. What you could do is just use the object’s type information:

public AddShape<T>(T shape) where T : Shape
{
    dict.Add(shape.GetType().FullName, shape.SerializableShape);
}
like image 192
Sami Kuhmonen Avatar answered Apr 06 '23 01:04

Sami Kuhmonen


Because nameof uses type information at compile time and would use the name as string from there but for a generic type T compiler cannot figure that out at compile time as it would be passed as parameter from where it would be consumed as it can be Shape or any subtype of it and that's the reason that it would be initialized at runtime, so that is why it cannot be used like above.

I also found this related which will also help:

https://stackoverflow.com/a/29878933/1875256

Hope it helps

like image 31
Ehsan Sajjad Avatar answered Apr 06 '23 00:04

Ehsan Sajjad