Question

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.

Was it helpful?

Solution

Use GetGetMethod() of PropertyInfo:

typeof(IBar).GetProperty("IsBar").GetGetMethod().Name
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top