Reputation: 123
Could anyone help me for this case:
public class MyClass
{
public int MyProperty{ get; set; }
private void MyMethod()
{
// here I wat to get the name of MyProperty.
// string name = "MyProperty"; <-- I don't want to hardcode it like this.
}
}
I don't want to hardcode it. Is it posible?
Thnak you
Upvotes: 2
Views: 96
Reputation: 1500125
One option is to use an expression tree:
var name = ExpressionTrees.GetPropertyName<MyClass, int>(x => x.MyProperty);
...
public static class ExpressionTrees
{
public static string GetPropertyName<TSource, TTarget>
(Expression<Func<TSource, TTarget>> expression)
{
...
}
}
(Alternative approaches can help with type inference, but I'm cutting to the chase here.)
If you rename MyProperty
, then if you do it as a refactoring your usage in the call to GetPropertyName
will also change, and if otherwise you'll get a compile-time failure.
There are numerous posts on Stack Overflow for how to extract the name from the expression tree, but it's worth being aware that this is still potentially flawed approach - there's nothing to stop you from writing:
ExpressionTrees.GetPropertyName<MyClass, int>(x => 0);
You can detect that at execution time, but not at compile time. There's also the matter of performance - it won't be dreadful, but it may not be ideal.
Depending on your requirements (in this case exactly why you want to identify that property rather than another one) then other approaches may work well, such as attributes.
Upvotes: 7