0

This is the kind of code I'd like to make work:

string Name = GetPropName(myClass.SomeProperty); // returns "SomeProperty"

Because I might be renaming my class' properties, I wouldn't like to forget to change their string names somewhere in my code, and there are quite a few places I use string names for properties, so I'd like to have this handy method to get the current name of a property as string for me. How do I do this?

What I'm after is a method that returns only the string name of the property it receives as a parameter.

I see there have been similar questions asked before, but there are no answers that explain well how to do what I'm trying to do.

user1306322
  • 8,561
  • 18
  • 61
  • 122
  • See http://stackoverflow.com/a/3269604/880990 – Olivier Jacot-Descombes Jun 11 '13 at 16:08
  • do you want something like GetPropName(x=>x.PropName); – adt Jun 11 '13 at 16:15
  • @adt I don't know, do I? – user1306322 Jun 11 '13 at 16:16
  • yes actually linked answers http://stackoverflow.com/questions/2820660/get-name-of-property-as-a-string should worrk. since you dont want to use prop names as string exposing them with expression might work for you – adt Jun 11 '13 at 16:17
  • @OlivierJacot-Descombes your answer doesn't work for me − VS can't seem to find `Expression` and `MemberExpression`, even though the `System.Linq` namespace is being used. Maybe this is from older version of .Net or something. – user1306322 Jun 11 '13 at 16:18
  • @user1306322: See namespace `System.Linq.Expressions`. VS will show you a smart tag revaling the namespace, once you have typed the type names (including the generic type parameters)... – Olivier Jacot-Descombes Jun 11 '13 at 16:23
  • net 4.5 supports expression and all sort of the things. – adt Jun 11 '13 at 16:28
  • @OlivierJacot-Descombes ok, it got those types working, but there is not an example of use and I can't figure out myself. Can you maybe post an answer here with an example? – user1306322 Jun 11 '13 at 16:28

1 Answers1

5

The problem with calling the method and passing in MyClass.MyProperty is that the value of the property is sent to the method. You can try and use reflection to get the property name from that value, but there are two issues with that:

1 - The property needs to have a value.

2 - If two properties of the same type have the same values, there's no way (at least as far as I know) to differentiate the two.

What you could do though is use an Expression to pass the property into the method, get the body of that expression and finally the member (property) name:

 public static string GetPropertyName<T, P>(Expression<Func<T, P>> propertyDelegate)
 {
     var expression = (MemberExpression)propertyDelegate.Body;
     return expression.Member.Name;
 }

And to use it:

string myPropertyName = GetPropertyName((MyClass x) => x.SomeProperty);
Arian Motamedi
  • 7,123
  • 10
  • 42
  • 82