KeyPress += LogKeyEvent;
Likewise the thread creation code becomes simply
Thread t = new Thread (MyMethod);
The readability differences between the original and the ???streamlined??? versions aren??™t
huge for a single line, but in the context of a significant amount of code, they can
reduce the clutter considerably. To make it look less like magic, let??™s take a brief look
at what this conversion is doing.
First, let??™s consider the expressions LogKeyEvent and MyMethod as they appear in
the examples. The reason they??™re classified as method groups is that more than one
method may be available, due to overloading. The implicit conversions available will
convert a method group to any delegate type with a compatible signature. So, if you
had two method signatures as follows:
void MyMethod()
void MyMethod(object sender, EventArgs e)
you could use MyMethod as the method group in an assignment to either a ThreadStart
or an EventHandler as follows:
ThreadStart x = MyMethod;
EventHandler y = MyMethod;
However, you couldn??™t use it as the parameter to a method that itself was overloaded to
take either a ThreadStart or an EventHandler??”the compiler would complain that
the conversion was ambiguous. Likewise, you unfortunately can??™t use an implicit
141 Covariance and contravariance
method group conversion to convert to the plain System.Delegate type since the
compiler doesn??™t know which specific delegate type to create an instance of.
Pages:
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291