csharp notes – 2
1. delegate Compatibility
1) Type compatibility
Delegate types are all incompatible with each other, even if their signatures are the same
delegate void D1( ); delegate void D2( ); ...
D1 d1 = Method1;
D2 d2 = d1; // compile-time error
Delegate instances are considered equal if they have the same method targets:
delegate void D( ); ... D d1 = Method1; D d2 = Method1; Console.WriteLine (d1 == d2); // true2) Parameter compatibility
When you call a method, you can supply arguments that have more specific types than the parameters of that method. This is ordinary polymorphic behavior. For exactly the same reason, a delegate can have more specific parameter types than its method target. This is called contravariance.
[from small to big]
3) Return type compatibility
If you call a method, you may get back a type that is more specific than what you asked for. This is ordinary polymorphic behavior. For exactly the same reason, the return type of a delegate can be less specific than the return type of its target method. This is called covariance. Consider the following example:
[from big to small]
2. The main purpose of events is to prevent subscribers from interfering with each other.
3. With explicit event accessors, you can apply more complex strategies to the storage and access of the underlying delegate. There are three scenarios where this is useful:
-
When the event accessors are merely relays for another class that is broadcasting the event
-
When the class exposes a large number of events, where most of the time very few subscribers exist, such as a Windows control. In such cases, it is better to store the subscriber's delegate instances in a dictionary, since a dictionary will contain less storage overhead than dozens of null delegate field references
-
When explicitly implementing an interface that declares an event