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?

Was it helpful?

Solution

This question has been asked before, and it can done through the CodeDom api. See this and this. Note that those keywords (int, bool, etc.) are language specific, so if you are outputting this for a general .NET consumer the framework type names are usually preferred.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top