Are delegates copied during assignment to an event?
- by Sir Psycho
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);
}
}
}