Let's say we have a property as below
public string SomeProperty
{
get
{
var propName = "SomeProperty";
return "<" + propName + ">";
}
}
How can I set value of the above variable propName
to be the property name by reading from the assembly information itself?
Edit
Why we need this?
I'm using the WPF d:DataContext
as mentioned in here which will help me to display a 'design-mode' value for bound properties - very often, the bound values are displayed as empty string in design mode. And in the 'design-mode' data-context class, I want to return the property name for every binding properties I may have.
Hope this would explain your concerns.
In the Advanced Object lessons, in the Getter unit: “Another thing to keep in mind when using getter (and setter) methods is that properties cannot share the same name as the getter/setter function.”
The getter and setter method gives you centralized control of how a certain field is initialized and provided to the client, which makes it much easier to verify and debug. To see which thread is accessing and what values are going out, you can easily place breakpoints or a print statement.
Getters and setters are used to protect your data, particularly when creating classes. For each instance variable, a getter method returns its value while a setter method sets or updates its value. Given this, getters and setters are also known as accessors and mutators, respectively.
Declare the property like this, note that the new PropertyMetadata specifies a static method to call when the property is changed.
After a while I figure out a solution as below, which is quite convenient to me.
string SomeProperty
{
get
{
return GetDesignModeValue(() => this.SomeProperty);
}
}
string GetDesignModeValue<T>(Expression<Func<T>> propertyExpression)
{
var propName = (propertyExpression.Body as MemberExpression).Member.Name;
var value = string.Format(
"<{0}>"
, propName);
return value;
}
So, from now on, it is much much easier for us to show the binding properties' mocking
value when in design mode.
I hope you would find it helpful somedays!
There isn't a reliable way for doing that at runtime, but you can use MethodBase.GetCurrentMethod().Name
and throw away the first four characters.
This approach has some flaws: running the binary through an obfuscation tool may cause the method to get renamed. Additionally, the method may be inlined and cause problems (if you just use Remove
on the string without checking the length, it may even cause unexpected crashes in the Release build that can be difficult to reproduce in Debug mode).
If your code follows a pattern and you need to generate a bunch of properties like that, it's better to use a compile-time approach like a code generator or an aspect-oriented programming framework.
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