Follow me on Twitter RSS FEED

Friendly Name of Generic Type

Posted in
There is a C# Class, Type, which can be used to get details about other classes.
  Type t = typeof(string);
  Debug.WriteLine(t.Name);
This prints out "String". When you get the value of the property Name when t is assigned to a generic type...
  Type t = typeof(List<string>);
  Debug.WriteLine(t.Name);
This prints out "List`1`".

Problem: Type.Name does not return friendly names for generic types.

So I wrote an extension method, which returns the friendly name for any Type.
  public static string GetFriendlyName(this Type type)
  {
      if (type.IsGenericType)
     {
         StringBuilder sb = new StringBuilder();
         sb.Append(type.Name.Remove(type.Name.IndexOf('`')));
         sb.Append("<");
         Type[] arguments = type.GetGenericArguments();
         for(int i = 0; i < arguments.Length; i++)
         {
             sb.Append(arguments[i].GetFriendlyName());
             if (i + 1 < arguments.Length)
             {
                  sb.Append(", ");
              }
          }
          sb.Append(">");
          return sb.ToString();
      }
      else
      {
          return type.Name;
      }
  }
It's used like this:
  Type t = typeof(List<String>);
  Debug.WriteLine(t.GetFriendlyName());
This prints out "List<String>"

0 comments:

Post a Comment