- Reference types
- Type safe , instances of objects with their own properties and methods.
- Declare a delegate type,define a variable of a delegate type,create an instance of a delegate.
- Used to indirectly call one or more methods at run time,pass a delegate by ref as a parameter of a method
- Method is not specified when declaring the delegate type or a variable based on the delegate type
- Invoking Method is specified when an instance of delegate is created and dynamically associate one or more instances with the variable at runtime.
Uses:
- In creation of events. e.g. all events in 2.0 based on delegate types
- creation of asynchronous method calls.e.g. callbacks in 2.0 based on delegate types
- If you have two objects that have similar methods with identical method signatures, you can use the same delegate to invoke them even if two objects are not related,methods have different names.
- You can use generics in delegate signatures. By using generics, you can instantiate a strongly typed delegate that can be used at run time with full type safety without specifying a particular type in the signature of your delegate type declaration.This helps you create an event in a generic class and specify the return type and parameter types when you create an instance of the delegate.
- Invoke static or instance methods
- In C#,you can have anonymous methods
Types:
- A singlecast delegate references only a single method.
- A multicast delegate references many methods . All delegates are implicitly multicast delegates. By adding multiple method references to a delegate’s invocation list, you can invoke all the methods with one call to the delegate.This process is referred to as multicasting. You can invoke each method in the invocation list individually. This is useful if you want to determine the return value or output parameters of each method call or if you do not want to call certain methods in certain circumstances.
C# exeception rules to delegate
Covariance : occurs when the return type of the method referenced by the delegate inherits from the return type of the delegate itself. Because the method’s return type inherits from the delegate’s return type, the signatures are still considered a match.
Contravariance :Contravariance permits the declaration of a delegate with parameters that inherit from the types used in the parameters of the method that will be invoked. However, for contravariance to work, the order and number of parameters in the signatures of the delegate as well as the method must still match.
No comments:
Post a Comment