Search code examples
c#reflectioncompiler-construction.net-4.5method-names

Are there any classes which can supply you with what a MethodInfo/method name would be?


I was wondering if there are any classes which can generate a MethodBase/MethodInfo, or simply generate the method name, without using "magic strings". Right now I'm doing the following:

public void Foo(MethodInfo method)
{
    if (String.Equals("get_IsBar", method.Name, StringComparison.Ordinal))
    {
        // ...
    }
}

Instead, I was wondering if there is some way of getting the name, "get_IsBar", from an interface, something like this:

public interface IBar
{
    bool IsBar { get; }
}

public void Foo(MethodInfo method)
{
    string barMethodName = GetBarGetterMethodName(typeof(IBar), "IsBar");
    if (String.Equals(barMethodName, method.Name, StringComparison.Ordinal))
    {
        // ...
    }
}

I realize that there is still a "magic string" in there, but at least it's more manageable.


Solution

  • Use GetGetMethod() of PropertyInfo:

    typeof(IBar).GetProperty("IsBar").GetGetMethod().Name