Nick said:
I don't understand exactly what does the follow istruction do?
"monitor.DeviceNotification += delegate(object sender,
DeviceNotificationArgs e)"
This is just a C# 2.0 (or higher) language feature to make the creation of
short delegate methods easier.
In this case the DeviceStatusMonitor class exposes a DeviceNotification
event, so you need to hook up an event handler to handle it.
You could write an external method such as the following
void MyEventHandlerMethod(object sender, DeviceNotificationArgs e)
{
string message = string.Format("Disk {0} has been {1}", e.DeviceName,
e.DeviceAttached ? "inserted" : "removed");
MessageBox.Show(message, "Disk Status");
}
and then hook it up as follows
monitor.DeviceNotification += new
DeviceNotificationEventHandler(MyEventHandlerMethod);
However since there is not much code in the event handler sometimes it can
be more conveniant to define the event handler inline within the setup code.
monitor.DeviceNotification += delegate(object sender, DeviceNotificationArgs
e)
{
... same code as was in the external method ...
};
Essentially it's just the code to declare a method and to hook up the event
handler merged into one C# statement.
It's call an anonymous delegate (as you can't refer to the method that is
created via a name). It's essentially a little syntatic sugar as behind the
scenes the C# compiler is generating a standard method but giving it a
"random" name (use a tool such as reflector to take a look at the generated
code).
You can refer to the Anonymous Methods section of the C# Programming Guide
available on MSDN for a better description -
http://msdn.microsoft.com/en-us/library/0yw3tz5k(VS.80).aspx
C# 3.0 also improves the situation even further with a feature called lamba
expressions (
http://msdn.microsoft.com/en-us/library/bb397687.aspx) which
can reduce the amount of syntax required even further.
Hope this helps,
Christopher Fairbairn