I have implemented a strongly typed implementation of INotifyPropertyChanged, except instead of using the interface, I have added a base class to implement.
It works fine, but the bit I am struggling with is why TValue is used in the base method declaration (I did use this section from some code I found online)
NotifyPropertyUpdate<TValue>(…
BUT in the derived class, it doesn’t need to pass TValue at all!
What tells the compiler to resolve this at runtime instead of complaining at build?
Thanks,
Base class:
public class NotifyFuncPropertyChanged<T> : INotifyPropertyChanged
{
#region Implementation of INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyUpdate<TValue>(Expression<Func<T, TValue>> selector)
{
//get memberInfo from object selection
MemberInfo memberInfoSelection;
Expression body = selector;
if (body is LambdaExpression)
{
body = ((LambdaExpression)body).Body;
}
switch (body.NodeType)
{
case ExpressionType.MemberAccess:
memberInfoSelection =((MemberExpression)body).Member;
break;
default:
throw new InvalidOperationException();
}
//send notifyupdate to memberInfo
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(memberInfoSelection.Name));
}
}
#endregion
}
Usage (derived class)
public class NameTest : NotifyFuncPropertyChanged<NameTest>
{
public string Name { get; set; }
public void TestUpdateName()
{
this.NotifyPropertyUpdate(x => x.Name);
}
}
The C# compiler has a feature called Type inference. You can read about it in all its complexity in the language specification, in section 7.5.2, or there’s a very brief introduction here.
From the spec: