Is there a way to convert "int" to typeof(int) in c#?

Viewed 149

I know that I can obtain a type from string name like so

Type intType = Type.GetType("System.Int32");

But, what if I have string like so

string[] typeNameArr = new string[] {"Int", "String", "DateTime", "Bool"};

How to convert these to actual types? Maybe I can get full qualified name out of an alias and then do the GetType?

2 Answers

If you use fully qualified names, like "System.Int32" in the end you'll be able to to it through linq:

var types = typeNameArr.Select(c => Type.GetType(c));

Additionally: if your web-service provide custom names, you either need a mapping or a convention. E.g.:

var types = typeNameArr.Select(c => Type.GetType("System." + c));

or

var types = typeNameArr.Select(c => 
{
   switch (c)
   {
      "Int":
          return typeof(int);
      "Foo":
          return typeof(BarClass);  
      default:
          return  null
   }        
});

To get all primitive types with their alias you can write:

string assemblyFullName = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
var assembly = Assembly.Load(assemblyFullName);
var primitiveTypes =
    assembly.DefinedTypes.Where(definedType => definedType.IsPrimitive && definedType != typeof(IntPtr) && definedType != typeof(UIntPtr));

using (var provider = new CSharpCodeProvider())
{
    var result = primitiveTypes.Select(x => (Alias: provider.GetTypeOutput(new CodeTypeReference(x)), Type: x));
}

Would result in:

bool    typeof(Boolean)
byte    typeof(Byte)
char    typeof(Char)
double  typeof(Double)
short   typeof(Int16)
int     typeof(Int32)
long    typeof(Int64)
sbyte   typeof(SByte)
float   typeof(Single)
ushort  typeof(UInt16)
uint    typeof(UInt32)
ulong   typeof(UInt64)
Related