Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get user-friendly name of simple types through reflection?

Type t = typeof(bool);
string typeName = t.Name;

In this simple example, typeName would have the value "Boolean". I'd like to know if/how I can get it to say "bool" instead.

Same for int/Int32, double/Double, string/String.

like image 311
Cristian Diaconescu Avatar asked Jan 06 '11 13:01

Cristian Diaconescu


3 Answers

using CodeDom;
using Microsoft.CSharp;

// ...

Type t = typeof(bool);

string typeName;
using (var provider = new CSharpCodeProvider())
{
    var typeRef = new CodeTypeReference(t);
    typeName = provider.GetTypeOutput(typeRef);
}

Console.WriteLine(typeName);    // bool
like image 181
LukeH Avatar answered Nov 16 '22 16:11

LukeH


The "friendly names" as you call them are language-specific and not tied to the framework. Therefore, it doesn't make sense to have this information in the framework, and the MS design guidelines require you to use the framework names for method names etc. (such as ToInt32 etc.).

like image 4
Lucero Avatar answered Nov 16 '22 16:11

Lucero


From what I understand, bool, string, int, etc. are just aliases for us C# developers.

After the compiler processes a file, no more of them are acutally present.

like image 3
Uwe Keim Avatar answered Nov 16 '22 17:11

Uwe Keim