I have seen on another post this and its confusing me…
public class MyClass : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
public string MyProperty
{
set
{
if (_myProperty != value)
{
_myProperty = value;
NotifyPropertyChanged("MyProperty");
}
}
}
}
MyClass myClass = new MyClass();
myClass.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e)
{
actual = e.PropertyName;
};
I’m wondering about the last few lines are doing to be honest, why would the user be assiging a delegate to an event? Would’t they assign a method to it (as an event handler) or even an anonymous method as the event handler?
I thought that events were meant to encapsulate delegates…..?
This syntax was introduced in C# 2.0
They are using an anonymous method here, rather than having to create an actual instance method of the class. It’s generally considered cleaner.
In C# 3 and above, a Lambda expression could have been used as well.