Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically get a Type's Alias in .NET

Tags:

reflection

Is it possible to determine an object type's alias(es) through reflection? Given the following example where myObject is of type System.Int32 -- e.g

Type t = myObject.GetType();

t.Name will be Int32. However, I would like to identify the possibile alias(es), if any, of the objects in question, so that I could resolve the type name of int in addition to Int32

I'm not looking to spend a huge amount of time on this. If there isn't an extreamely simple, built in solution, I'll just map the values myself. =)

like image 484
George Johnston Avatar asked Mar 24 '26 10:03

George Johnston


2 Answers

Not directly with reflection, there is not. The "type name" (as you are calling it) "int" is not a type name at all, but a language keyword.

You could, of course, use a dictionary to store the look ups from type names to the shorter convenience forms. But there is nothing in the reflection API's that will do that for you.

like image 161
quentin-starin Avatar answered Mar 26 '26 13:03

quentin-starin


You can get language specific type alias by using CodeDom classes

    var cs = new CSharpCodeProvider();
    var vb = new VBCodeProvider();

    var type = typeof (int);
    Console.WriteLine("Type Name: {0}", type.Name); // Int32
    Console.WriteLine("C# Type Name: {0}", cs.GetTypeOutput(new CodeTypeReference(type))); // int
    Console.WriteLine("VB Type Name: {0}", vb.GetTypeOutput(new CodeTypeReference(type))); // Integer
like image 36
desco Avatar answered Mar 26 '26 14:03

desco