views:

72

answers:

1

Is it possible to rewrite this extension method without the parameter?

public static string PropertyName<T>(this T obj, Expression<Func<T>> property)
{
    var memberExpression = property.Body as MemberExpression;
    if (memberExpression == null)
        throw new ArgumentException("Expression must be a MemberExpression.", "property");
    return memberExpression.Member.Name;
}

This is the test code for the function.

string TEST = Guid.NewGuid().ToString();
string propertyName = TEST.PropertyName(() => TEST);

This is the result:

propertyName = "TEST"

I would like to rewrite the code to this:

string propertyName = TEST.PropertyName();

Ps. I'm not interested in a static version of this method!

For those how doesn’t see the point of this function. In MVVM pattern you have notify changed for a property. Like this.

this.RaisePropertyChanged("TEST");

This is a bad approach since the property name is hardcoded. With help of the extension method you will have this:

this.RaisePropertyChanged(()=>Test);

I would like to rewrite the extension method to this:

this.RaisePropertyChanged(Test.PropertyName());

Below is a code sample from my MVVM project. (this is a Model property)

public DateTime Start
{
    get { return WorkModel.Start; }
    set
    {
        if (WorkModel.Start != value)
        {
            WorkModel.Start = new DateTime(SelectedDate.Year, SelectedDate.Month, SelectedDate.Day, value.Hour, value.Minute, value.Second);
            this.RaisePropertyChanged("Start");
            this.RaisePropertyChanged("TotalWork");
        }
    }
}
+1  A: 

No this is not possible. Local variable name is only for compiler and is not recorded or can be renamed during compilation.

Of course properties are different thing. And you should be aware your first example is different from your second one.

Still, I dont see a way you can implement this. And even then it would be much bigger performance-killer than your working ()=>PropertyName kind of invocation.

Euphoric
When you use reflection you may need this function when you use obj.GetType().GetProperty("PropertyName")
Amir Rezaei