-1

Given this example, an extension method which uses the name of the type to return a value from a dictionary by it's type using generic T.

public static T GetItem<T>(this Dictionary<string, object> dictionary) 
{
    var y = nameof(T);
    var z = dictionary.FirstOrDefault(x => x.Key == y);
    return (T)z.Value;
}

And used as

var item = dictionary.GetItem<SomeClass>();

Is it possible to get the nameof(T) in the extension method above without providing any further parameters to the method? This appears to returns T instead of the expected SomeClass at runtime.

sharifxu
  • 25
  • 9
  • Does this answer your question? [How do I get the type name of a generic type argument?](https://stackoverflow.com/questions/2581642/how-do-i-get-the-type-name-of-a-generic-type-argument) –  Jun 03 '21 at 10:29
  • The type is returned by `typeof` not `nameof`. `nameof` returns the name of the thing it points to. In this case, the parameter name – Panagiotis Kanavos Jun 03 '21 at 10:30
  • I also have a question, if you really have a dictionary there, why are you using it as a list/array? You should be able to write your code as `var z = dictionary[y];`, no? – Lasse V. Karlsen Jun 03 '21 at 10:36

1 Answers1

2

It sounds like you should use

var y = typeof(T).Name; // y is "SomeClass"

or, if you want the namespace too,

var y = typeof(T).FullName; // y is "Namespace.For.SomeClass"

instead.

nameof will, as you discovered, return the name of the type parameter (i.e. "T") and not the name of the type that the generic method is invoked with (i.e. "SomeClass").

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92