Lesson 7. Events, Delegates, Generics. Programming in C# Lesson 7. Events, Delegates, Generics.
Delegates
What is a delegate? A delegate is a type safe pointer to a method (or a chain of methods) All delegates are classes that inherited from MulticastDelegate class Delegates are useful in callback scenarios Delegates are used in APM (Asynchronous Programming Model) Delegates are the base of events
Declaring a delegate delegate keyword Name Return value type Parameters (number and type)
Using a delegate
Using a delegate as a callback method
Using a delegate as a callback method
Delegates chaining
Delegates chaining
Using delegates in APM
Anonymous Methods and Lambda Expressions
Events Events provide a way for an object to be notified about something that has happened in another object
Designing a Type That Exposes an Event Define a type that will hold any additional information that should be sent to subscribers Define the event member (based on existing or custom delegate) Define a method responsible for raising the event Call the method responsible for raising the event from the appropriate place
Defining a type that will hold additional information
Defining the event member
Defining a method responsible for raising the event
Calling the method responsible for raising the event
Subscribing/Unsubscribing to events
Method GetInvocationList Method GetInvocationList allows us to iterate manually through the list of subscribers and handle them correspondingly:
EventHandler and EventHandler<TEventArgs> delegates In order to avoid the necessity to create custom delegates each time we need to expose an event, these standard delegates should be used:
Generics
What are generics? Generics provide another form of code reuse: algorithm reuse Generics allow us to encapsulate an algorithm within a class, interface or method without specifying the data type(s) that class or method works on Generics provide type safety Generics provide better performance (especially for collection data structures) as they prevent the necessity of boxing/unboxing and type casting There are generic classes, interfaces, methods and delegates
A generic class sample
Operator default Operator default specifies the default value of the type parameter. This will be null for reference types and zero for value types
Constraints on Type Parameters where T: struct – The type argument must be a value type where T: class – The type argument must be a reference type where T: new() – The type argument must have a public parameterless constructor where T: <base class name> – The type argument must be or derive from the specified base class where T: <interface name> – The type argument must be or implement the specified interface
Generic Class with Constraints Sample
Generic Method with Constraints Sample