-1

For example, I want to have a method to get typeof(int) from "int", typeof(List<int>) from "List<int>", typeof(Dictionary<string, int>) from "Dictionary<string,int>", etc.

If the friendly name is an ambiguous one in the calling context, it's ok to throw an exception or simply return a null.

I can use a dictionary to store the map for all built-in friendly types, but it would be too complicated to map every concrete generic type manually. I cannot find a way to build up all the friendly names I may need.

Is there some "eval" method in C# like in some script languages? I.e. so I can simply run typeof with the friendly name as input and get a Type object reference as the return value?

Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
TinglePan
  • 55
  • 6
  • I'm pretty sure you can use CSharpCodeDomProvider (or related) to do this. Roslyn APIs as well – pinkfloydx33 Jun 14 '21 at 12:29
  • 2
    Maybe you are looking for `Type.GetType` eg. https://learn.microsoft.com/en-us/dotnet/api/system.type.gettype?view=net-5.0#System_Type_GetType_System_String_ - in combination with avoiding the namespace eg. https://stackoverflow.com/questions/9273629/avoid-giving-namespace-name-in-type-gettype - which instead of in `Type.GetType("System.Int32");` could give you `Type.GetTypeWithoutNamespace("Int32");` – Rand Random Jun 14 '21 at 12:37
  • I don't think the post about avoiding namespace works for generic types. I believe the GetTypes method of an assembly does not return a concrete version of a generic type, which means I have to make the concrete types manually using every generic parameter I want to support. Tell me if I am mistaken. – TinglePan Jun 14 '21 at 12:48
  • The `typeof` keyword works only at compile time. To obtain a `Type` object dynamically at runtime, you need reflection. See duplicates for solutions to both the non-generic and generic scenarios. – Peter Duniho Jun 14 '21 at 19:11

1 Answers1

-1

You can use .GetType().Name to get type of an object in simple.

T.GetType().Name // class name, no namespace
T.GetType().FullName // namespace and class name
T.GetType().Namespace // namespace, no class name
Rostam Bamasi
  • 204
  • 1
  • 6
  • GetType requires the fully qualified name of a type, which cannot be obtained from the user input, and it's somehow complicated to build up one manually. – TinglePan Jun 14 '21 at 12:41
  • You can also use typeof(T) as the sample => typeof(T).Name // class name, no namespace typeof(T).FullName // namespace and class name typeof(T).Namespace // namespace, no class name – Rostam Bamasi Jun 14 '21 at 18:50
  • 2
    It seems to me you've misunderstood the question. All three of your example statements assume that you already have something from which you can obtain a `Type` object. The question is asking _how to obtain that `Type` object in the first place_. – Peter Duniho Jun 14 '21 at 19:10