Get MethodInfo Signature
-
11-12-2019 - |
Question
Say you have a MethodInfo relating to the method myMethod:
void myMethod(int param1, int param2) { }
and you want to create a string that represents the method's signature:
string myString = "myMethod (int, int)";
Looping through the MethodInfo parameters, I was able to achieve these results by calling the parameter types' ToString methods:
"myMethod (System.Int32, System.Int32)"
How can I improve on this and produce the results shown above?
OTHER TIPS
As far as I know, there is nothing built-in that will convert the real type name of a primitive (System.Int32
) to the built-in alias (int
). Since there is only a very small number of these aliases, it's not too difficult to write your own method:
public static string GetTypeName(Type type)
{
if (type == typeof(int)) // Or "type == typeof(System.Int32)" -- same either way
return "int";
else if (type == typeof(long))
return "long";
...
else
return type.Name; // Or "type.FullName" -- not sure if you want the namespace
}
That being said, if the user actually did type in System.Int32
rather than int
(which of course would be perfectly legal) this technique would still print out "int". There's not a whole lot you can do about that because the System.Type
is the same either way -- so there's no way for you to find out which variant the user actually typed.