0

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?

Abdulla
  • 1,117
  • 4
  • 21
  • 44
  • The case of `myMethod` should not have changed -- are you only referring to the `Sysetm.Int32` vs. `int` part? – Kirk Woll May 18 '12 at 19:23
  • Sorry, that was a typo which has now been fixed. Yes, my problem is with displaying a type's name the way it is declared. I'm wondering if there is a better solution than hard-coding a string for each type. – Abdulla May 18 '12 at 19:24

2 Answers2

0

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.

Kirk Woll
  • 76,112
  • 22
  • 180
  • 195
0

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.

Community
  • 1
  • 1
Mike Zboray
  • 39,828
  • 3
  • 90
  • 122