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.....?
You always subscribe to an event (or unsubscribe from it) using a delegate. Even if you do:
button.Click += HandleButtonClick;
that's equivalent to
button.Click += new EventHandler(HandleButtonClick);
When you say:
Would't they assign a method to it (as an event handler) or even an anonymous method as the event handler?
That's exactly what the last few lines of code do. That's what delegate (...) { ... } is.
I thought that events were meant to encapsulate delegates.....?
Events provide an implementation of the observer pattern, using delegates as the observers.
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.
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