Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone explain what is happening behind the scenes?

Tags:

c#

.net

events

It's not entirely obvious to me what's happening in this situation.

I'd expect both functions to be fired.

Either the EventHander class is storing the list of functions to fire as an array - and the array is copied to a new one every time something is added/removed - or when the assignment is made, the whole thing is copied to a new "collection" - and not just a reference.

Somebody please enlighten me :D

Here's a little Linqpad script:

public class Moop
{
    public EventHandler myEvent;
}

void Main()
{
    var moo = new Moop();
    moo.myEvent += (o, sender) => { "Added to Moop #1".Dump(); };   

    var moo2 = new Moop();

    //Copy the reference, I assume?
    moo2.myEvent = moo.myEvent;

    moo2.myEvent += (o, sender) => { "Added to Moop #2".Dump(); }; 

    //Fire the event on #1
    moo.myEvent(null, null);
}
like image 497
Dave Bish Avatar asked Apr 02 '12 14:04

Dave Bish


People also ask

What do you call someone who works behind the scenes?

A stagehand is a person who works backstage or behind the scenes in theatres, film, television, or location performance.

How do you explain what a scene is?

A scene is a section of your novel where a character or characters engage in action or dialogue. You can think of a scene as a story with a beginning, middle, and an end. A chapter can contain one scene or many scenes.

Why is working behind the scenes important?

Why you should utilise behind the scenes content: It allows the audience to have a deeper understanding of the work involved in your company. This adds value as the client experiences a human connection and learns more from the overall product or service. It also helps to build trust and loyalty.

What is behind the scenes in a movie?

In cinema, behind-the-scenes (BTS), also known as the making-of, the set, or on the set, is a type of documentary film that features the production of a film or television program.


1 Answers

Event handler lists are delegates, and delegates are immutable -- like strings. So you do copy the delegate, and the second event handler gets "added to" the 2nd delegate, not the first.

You can find out more about delegates at http://www.c-sharpcorner.com/uploadfile/Ashush/delegates-in-C-Sharp/

Good luck!

like image 174
Roy Dictus Avatar answered Sep 23 '22 23:09

Roy Dictus