Print full signature of a method from a MethodInfo

.net, c#, debugging, reflection

Solution

Unfortunately I don't believe there is a built in method that would do that. Your best be would be to create your own signature by investigating the MethodInfo class

EDIT: I just did this

 MethodBase mi = MethodInfo.GetCurrentMethod();
 mi.ToString();

and you get

Void Main(System.String[])

This might not be what you're looking for, but it's close.

How about this

public static class MethodInfoExtension
{
    public static string MethodSignature(this MethodInfo mi)
    {
        String[] param = mi.GetParameters()
                           .Select(p => String.Format("{0} {1}",p.ParameterType.Name,p.Name))
                           .ToArray();

        string signature = String.Format("{0} {1}({2})", mi.ReturnType.Name, mi.Name, String.Join(",", param));

        return signature;
    }
}

var methods = typeof(string).GetMethods().Where( x => x.Name.Equals("Compare"));
    
foreach(MethodInfo item in methods)
{
    Console.WriteLine(item.MethodSignature());
}

This is the result

Int32 Compare(String strA,Int32 indexA,String strB,Int32 indexB,Int32 length,StringComparison comparisonType)

Problem

Is there any existing functionality in the .NET BCL to print the full signature of a method at runtime (like what you'd see in the Visual Studio ObjectBrowser - including parameter names) using information available from MethodInfo? So for example, if you look up String.Compare() one of the overloads would print as: ``` public static int Compare(string strA, int indexA, string strB, int indexB, int length, bool ignoreCase, System.Globalization.CultureInfo culture) ``` Note the presence of the complete signature with all access and scope qualifiers as well as a complete list of parameters including names. This is what I'm looking for. I could write my own method, but I would rather use an existing implementation if possible.

Original source