How do you get the C # property name as a reflection string?

Possible duplicate:
C # - How do you get the name of a variable since it was physically printed in the declaration?

I am looking for a way to get the property name as a string so that I have a "strongly typed" magic string. I need to do something like MyClass.SomeProperty.GetName (), which will return "SomeProperty". Is this possible in C #?

+7
reflection c #
source share
3 answers

You can use expressions to achieve this quite easily. See this blog for an example .

This makes it so that you can create an expression via lambda and pull out the name. For example, the implementation of INotifyPropertyChanged could be redesigned to do something like:

public int MyProperty { get { return myProperty; } set { myProperty = value; RaisePropertyChanged( () => MyProperty ); } } 

To map the equivalent using the Reflect reference class, you would do something like:

 string propertyName = Reflect.GetProperty(() => SomeProperty).Name; 

Viola - property names without magic lines.

+6
source share

This approach will be faster than using Expression

 public static string GetName<T>(this T item) where T : class { if (item == null) return string.Empty; return typeof(T).GetProperties()[0].Name; } 

Now you can call it:

 new { MyClass.SomeProperty }.GetName(); 

You can cache values โ€‹โ€‹if you need even more performance. See This duplicate question. How do you get the name of a variable since it was physically printed in its declaration?

+8
source share

You can get a list of object properties using reflection.

 MyClass o; PropertyInfo[] properties = o.GetType().GetProperties( BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance ); 

Each property has a Name attribute that will provide you with "SomeProperty"

+1
source share

All Articles