The way to convert generic type into C# string representation

Today I’ve faced with task to convert variable of type Type (wich can be generic) into string exression. For example, I have such variable:
Type someType = typeof(Dictionary);
and I need to have C#-string representation of this type as follows: “Dictionaнy<Int32,String>“. Quite useful during T4-templates generation.
Here is small code snippet for that:

public class GenericTypeFormatter
{
private const char GenericTypeParameterPrefix = '<';
private const char GenericTypeParameterSuffix = '>';
public static string GenericTypeToString(Type type)
{
if (!type.IsGenericType) return type.Name;
Type[] args = type.GetGenericArguments();

StringBuilder joinedTypeArgs = new StringBuilder();
foreach (Type t in args)
{
if (joinedTypeArgs.Length > 0) joinedTypeArgs.Append(",");
joinedTypeArgs.Append(GenericTypeToString(t));
}

return
type.GetGenericTypeDefinition().Name.Replace("`" + args.Length, "") +
GenericTypeParameterPrefix +
joinedTypeArgs +
GenericTypeParameterSuffix;
}
}

Добавить комментарий

Fill in your details below or click an icon to log in:

Логотип WordPress.com

You are commenting using your WordPress.com account. Log Out / Изменить )

Фотография Twitter

You are commenting using your Twitter account. Log Out / Изменить )

Фотография Facebook

You are commenting using your Facebook account. Log Out / Изменить )

Connecting to %s

Follow

Get every new post delivered to your Inbox.