Possible Duplicate:
c# - How do you get a variable’s name as it was physically typed in its declaration?
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#?
This approach will be way 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 a variable's name as it was physically typed in its declaration?
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With