Home > Software design >  Need help understanding an event being assigned "delegate { }"
Need help understanding an event being assigned "delegate { }"

Time:02-08

While looking at an UWP example app, I came across this code. What I don't understand and can't seem to find in google is line 40:

        public event PropertyChangedEventHandler PropertyChanged = delegate { };

Says in the comments that it is a multicast event. What does assigning delegate { } do? Does it have anything to do with the comment saying the event is multicast?

CodePudding user response:

What does assigning delegate { } do?

That is simply adding an anonymous function to the event, with an empty body. Since C#3, one would generally use a lambda expression instead:

public event PropertyChangedEventHandler PropertyChanged = (s, e) => { };

However, lambda expressions require each parameter to be elicited, whereas using delegate does not. So if you don't need to use the arguments, then delegate may be more concise.

Microsoft highlight this as the single remaining use case of the delegate syntax for defining an anonymous function:

When you use the delegate operator, you might omit the parameter list. If you do that, the created anonymous method can be converted to a delegate type with any list of parameters. That's the only functionality of anonymous methods that is not supported by lambda expressions. In all other cases, a lambda expression is a preferred way to write inline code.

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/delegate-operator

Does it have anything to do with the comment saying the event is multicast?

No; multicast means that you can add more than one handling function to the event, and when the event is raised, each one is invoked.

For example:

class Example
{
    public event PropertyChangedEventHandler PropertyChanged;

    public void RaiseEvent()
    {
        PropertyChanged?.Invoke(default, default);
    }
}

var example = new Example();

// Use the  = operator to add a new handler (rather than = which overwrites)
example  = delegate { Console.Writeline("Handler 1"); };
example  = delegate { Console.Writeline("Handler 2"); };

example.RaiseEvent();

// Output:
// Handler 1
// Handler 2

Follow up question: What is the purpose of assigning an anonymous function to the event?

If no handler has been added, invoking the event can cause a NullReferenceException, so assigning an empty handler could remove the necessity to handle null.

So the event can be raised like this:

PropertyChanged.Invoke(default, default);

Or this:

PropertyChanged(default, default);

Rather than this:

PropertyChanged?.Invoke(default, default);

CodePudding user response:

It's just an empty delegate, but the compiler will derive delegates from MulticastDelegate. So all delegates in C# are multicast.

Action d = delegate { };
// True
Console.WriteLine(d.GetType().BaseType == typeof(MulticastDelegate));
  •  Tags:  
  • Related