I'm looking for a way to get a property name as a string so I can have a "strongly-typed" magic string. What I need to do is something like MyClass.SomeProperty.GetName() that would return "SomeProperty". Is this possible in C#?
+4
A:
You can use Expressions to achieve this quite easily. See this blog for a sample.
This makes it so you can create an expression via a lambda, and pull out the name. For example, implementing INotifyPropertyChanged can be reworked to do something like:
public int MyProperty {
get { return myProperty; }
set
{
myProperty = value;
RaisePropertyChanged( () => MyProperty );
}
}
In order to map your equivalent, using the referenced "Reflect" class, you'd do something like:
string propertyName = Reflect.GetProperty(() => SomeProperty).Name;
Viola - property names without magic strings.
Reed Copsey
2009-11-03 17:49:15
The syntax here is a bit nasty, but it does do what I needed it to. Thanks!
jcm
2009-11-03 20:53:02
+1
A:
You can get a list of properties of an object using reflection.
MyClass o;
PropertyInfo[] properties = o.GetType().GetProperties(
BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance
);
Each Property has a Name attribute which would get you "SomeProperty"
David Liddle
2009-11-03 17:53:51