Are delegates copied during assignment to an event?

Posted by Sir Psycho on Stack Overflow See other posts from Stack Overflow or by Sir Psycho
Published on 2010-04-26T07:32:24Z Indexed on 2010/04/26 7:43 UTC
Read the original article Hit count: 304

Filed under:
|
|

Hi,

The following code seems to execute the FileRetrieved event more than once. I thought delegates were a reference type. I was expecting this to execute once. I'm going to take a guess and say that the reference is being passed by value, therefore copied but I don't like guesswork :-)

public delegate void DirListEvent<T>(T dirItem);

void Main()
{
    DirListEvent<string> printFilename = s => {
        Console.WriteLine (s);
    };

    var obj = new DirectoryLister();

    obj.FileRetrieved += printFilename;
    obj.FileRetrieved += printFilename;

    obj.GetDirListing();
}

public class DirectoryLister {

    public event DirListEvent<string> FileRetrieved;


    public DirectoryLister() {
        FileRetrieved += delegate {};
    }

    public void GetDirListing() {

        foreach (var file in Directory.GetFiles(@"C:\"))
        {
            FileRetrieved(file);
        }
    }
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about events