Cristian Diaconescu
Cristian Diaconescu

Reputation: 35651

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.

Upvotes: 22

Views: 7642

Answers (7)

LukeH
LukeH

Reputation: 269408

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

Upvotes: 47

CodesInChaos
CodesInChaos

Reputation: 108810

The .net framework itself doesn't know about C# specific keywords. But since there are only about a dozen of them, you can simply manually create a table containing the names you want.

This could be a Dictionary<Type,string>:

private static Dictionary<Type,string> friendlyNames=new Dictionary<Type,string>();

static MyClass()//static constructor
{
  friendlyNames.Add(typeof(bool),"bool");
  ...
}

public static string GetFriendlyName(Type t)
{
  string name;
  if( friendlyNames.TryGet(t,out name))
    return name;
  else return t.Name;
}

This code doesn't replace Nullable<T> with T? and doesn't transform generics into the form C# uses.

Upvotes: 1

Moo-Juice
Moo-Juice

Reputation: 38825

You could always create a dictionary to translate the C# names to the "friendly" ones you want:

Dictionary<System.Type, string> dict = new Dictionary<System.Type, string>();
dict[typeof(System.Boolean)] = "bool";
dict[typeof(System.string)]  = "string";
// etc...

Upvotes: 1

jjrdk
jjrdk

Reputation: 1892

I'd say you can't since those names are specific to C# and as such will not produce the same result if the developer wanted to use VB.NET.

You are getting the CLR type and that is really what you would want to be able to recreate the type later. But you can always write a name mapper.

Upvotes: 0

Carlo Kok
Carlo Kok

Reputation: 1168

you can't. Those are all C# specific keywords. But you can easily map them:

switch (Type.GetTypeCode(t)) {
  case TypeCode.Byte: return "byte";
  case TypeCode.String: return "string";
}

etc

Upvotes: 1

Uwe Keim
Uwe Keim

Reputation: 40736

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.

Upvotes: 3

Lucero
Lucero

Reputation: 60190

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.).

Upvotes: 4

Related Questions