I was working on some TT code generation to get rid of mundane C# codings in VS2013 Express Edition, and after researching online, created the following helper methods to facilitate Type declarations.
I am able to use it successfully in my code generation but wonder if they can be improved further or if there's any scenario which they do not cater for.
public static String GetActualTypeName(Type type, bool bAlias = true, bool bFullQualified = false)
{
Type nullable = Nullable.GetUnderlyingType(type);
String name = null;
if (nullable != null) // handles Nullable types
{
name = (bAlias) ? GetAliasName(nullable, bFullQualified)
: (bFullQualified) ? nullable.FullName : nullable.Name;
return String.Format("{0}?", name);
}
if (!type.GenericTypeArguments.Any()) // handles non generic types
{
name = (bAlias) ? GetAliasName(type, bFullQualified)
: (bFullQualified) ? type.FullName : type.Name;
return name;
}
name = (bFullQualified) ? type.FullName : type.Name;
// recrusive looping into generic type tree for the required type names
String[] names = type.GenericTypeArguments
.Select(t => GetActualTypeName(t, bAlias, bFullQualified))
.ToArray();
return String.Format("{0}<{1}>", name.Substring(0, name.IndexOf('`')), String.Join(",", names));
}
public static String GetAliasName(Type type, bool bFullQualified = false)
{
String alias = null;
using (var provider = new Microsoft.CSharp.CSharpCodeProvider())
{
var typeRef = new System.CodeDom.CodeTypeReference(type);
alias = provider.GetTypeOutput(typeRef);
}
int index = alias.LastIndexOf(".");
if (bFullQualified || index == -1)
return alias;
return alias.Substring(index + 1);
}