Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is this C# construct doing?

Tags:

c#

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.....?

like image 736
Exitos Avatar asked Feb 16 '26 20:02

Exitos


2 Answers

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.

like image 115
Jon Skeet Avatar answered Feb 21 '26 15:02

Jon Skeet


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.

like image 39
Erix Avatar answered Feb 21 '26 13:02

Erix



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!