If I have this:
Type t = typeof(Dictionary<String, String>);
How do I get "System.Collections.Generic.Dictionary"
as a string? Is the best/only way to do this:
String n = t.FullName.Substring(0, t.FullName.IndexOf("`"));
Seems kinda hackish to me though.
The reason I want this is that I want to take a Type
object, and produce code that is similar to the one found in a C# source code file. I'm producing some text templates, and I need to add types as strings into the source, and the FullName
property produces something like this:
System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089]]
instead of what I want:
System.Collections.Generic.Dictionary<System.String, System.String>
Edit: Ok, here's the final code, still seems a bit like a hack to me, but it works:
/// <summary>
/// This method takes a type and produces a proper full type name for it, expanding generics properly.
/// </summary>
/// <param name="type">
/// The type to produce the full type name for.
/// </param>
/// <returns>
/// The type name for <paramref name="type"/> as a string.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <para><paramref name="type"/> is <c>null</c>.</para>
/// </exception>
public static String TypeToString(Type type)
{
#region Parameter Validation
if (Object.ReferenceEquals(null, type))
throw new ArgumentNullException("type");
#endregion
if (type.IsGenericType)
{
if (type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
Type underlyingType = type.GetGenericArguments()[0];
return String.Format("{0}?", TypeToString(underlyingType));
}
String baseName = type.FullName.Substring(0, type.FullName.IndexOf("`"));
return baseName + "<" + String.Join(", ", (from paramType in type.GetGenericArguments()
select TypeToString(paramType)).ToArray()) + ">";
}
else
{
return type.FullName;
}
}