Alex Rivera | Logout

Print full signature of a method from a MethodInfo

Asked 2009-08-21T14:05:38.807
36

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.

Edit
Report

1 Answer

36

Update 3/22/2018

I've rewritten the code, added a few tests, and uploaded it to GitHub

It's also available through nuget

Eltons.ReflectionKit NuGet

Answer

using System.Text;

namespace System.Reflection
{
    public static class MethodInfoExtensions
    {
        /// <summary>
        /// Return the method signature as a string.
        /// </summary>
        /// <param name="method">The Method</param>
        /// <param name="callable">Return as an callable string(public void a(string b) would return a(b))</param>
        /// <returns>Method signature</returns>
        public static string GetSignature(this MethodInfo method, bool callable = false)
        {
            var firstParam = true;
            var sigBuilder = new StringBuilder();
            if (callable == false)
            {
                if (method.IsPublic)
                    sigBuilder.Append("public ");
                else if (method.IsPrivate)
                    sigBuilder.Append("private ");
                else if (method.IsAssembly)
                    sigBuilder.Append("internal ");
                if (method.IsFamily)
                    sigBuilder.Append("protected ");
                if (method.IsStatic)
                    sigBuilder.Append("static ");
                sigBuilder.Append(TypeName(method.ReturnType));
                sigBuilder.Append(' ');
            }
            sigBuilder.Append(method.Name);

            // Add method generics
            if(method.IsGenericMethod)
            {
                sigBuilder.Append("<&q
answered 2012-11-10T00:41:38.710

Your Answer