3

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?

TheLethalCoder
  • 6,668
  • 6
  • 34
  • 69
FIF
  • 223
  • 1
  • 2
  • 6
  • 1
    Can you provide any more context as to why you need to use reflection to achieve this? Perhaps we can suggest an alternative. – Mike Eason Nov 16 '15 at 13:11
  • Probably you must use GetType().GetProperty(nameof(Foo)).SetMethod ? – IgorL Nov 16 '15 at 13:14

2 Answers2

5

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;
Jakub Lortz
  • 14,616
  • 3
  • 25
  • 39
-1

Something like -

var type = typeof(Test).GetProperties().FirstOrDefault().GetAccessors(false);

where Test is the type with a property S3 of type string.

Amit Kumar Ghosh
  • 3,618
  • 1
  • 20
  • 24