Search code examples
c#nameof

Using nameof to get a setter method name in c#


Is it possible to get a setter method name using the new nameof operator?

public object Foo { get; set; }

public void Test()
{        
    var myMethod = GetType().GetMethod("set_Foo");       
}

I guess GetType().GetMethod("set_" + nameof(Foo)) could work but is there something more straightforward?


Solution

  • You can't use nameof to get the setter method name directly.

    You can combine it with reflection to get the property and use PropertyInfo.SetMethod to get the setter:

    MethodInfo setterMethod = GetType().GetProperty(nameof(Foo)).SetMethod;
    string setterName = setterMethod.Name;