Reputation: 5848
I need a function that will convert a type to a string, for example:
Dim foo as Dictionary(of Dictionary(of Integer, String), Integer)
Debug.WriteLine(TypeToString(GetType(foo)))
In the debug output, I'd expect to see something equivalent to:
Dictionary(of Dictionary(of Integer, String), Integer)
Upvotes: 3
Views: 1015
Reputation: 117175
Here's some extension methods I use to do what you ask, but it's in C# and generate C#.
You can either keep it in C#, but change the output to VB.Net or do a full conversion to VB.Net if you like.
public static string ToCode(this Type @this)
{
string @return = @this.FullName ?? @this.Name;
Type nt = Nullable.GetUnderlyingType(@this);
if (nt != null)
{
return string.Format("{0}?", nt.ToCode());
}
if (@this.IsGenericType & [email protected])
{
Type gtd = @this.GetGenericTypeDefinition();
return string.Format("{0}<{1}>", gtd.ToCode(), @this.GetGenericArguments().ToCode());
}
if (@return.EndsWith("&"))
{
return Type.GetType(@this.AssemblyQualifiedName.Replace("&", "")).ToCode();
}
if (@this.IsGenericTypeDefinition)
{
@return = @return.Substring(0, @return.IndexOf("`"));
}
switch (@return)
{
case "System.Void":
@return = "void";
break;
case "System.Int32":
@return = "int";
break;
case "System.String":
@return = "string";
break;
case "System.Object":
@return = "object";
break;
case "System.Double":
@return = "double";
break;
case "System.Int64":
@return = "long";
break;
case "System.Decimal":
@return = "decimal";
break;
case "System.Boolean":
@return = "bool";
break;
}
return @return;
}
public static string ToCode(this IEnumerable<Type> @this)
{
var @return = "";
var ts = @this.ToArray<Type>();
if (ts.Length > 0)
{
@return = ts[0].ToCode();
if (ts.Length > 1)
{
foreach (Type t in ts.Skip<Type>(1))
{
@return = @return + string.Format(", {0}", t.ToCode());
}
}
}
return @return;
}
Upvotes: 2
Reputation: 25569
Isn't foo.GetType().ToString()
acceptable for you? In the example case it will return
System.Collections.Generic.Dictionary`2[System.Collections.Generic.Dictionary`2[System.Int32,System.String],System.Int32]
Upvotes: 2