Introduction
Delegates in C# are like functions pointers in C/C++. A multi cast delegate can refer to several methods. A delegate can be used to invoke a method, the call to which can only be resolved or determined at runtime. This article discusses what delegates are and how they can be used in C# with lucid code examples.
What are delegates and why are they required?
Delegates are function pointers in C# that are managed and type safe and can refer to one or more methods that have identical signatures. Delegates in C# are reference types. They are type safe, managed function pointers in C# that can be used to invoke a method that the delegate refers to. The signature of the delegate should be the same as the signature of the method to which it refers. According to MSDN, "A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked. Unlike function pointers in C or C++, delegates are object-oriented, type-safe, and secure."
C# provides support for Delegates through the class called Delegate in the System namespace. Delegates are of two types.
· Single-cast delegates
· Multi-cast delegates
A Single-cast delegate is one that can refer to a single method whereas a Multi-cast delegate can refer to and eventually fire off multiple methods that have the same signature.
The signature of a delegate type comprises are the following.
· The name of the delegate
· The arguments that the delegate would accept as parameters
· The return type of the delegate
A delegate is either public or internal if no specifier is included in its signature. Further, you should instantiate a delegate prior to using the same.
reference: http://aspalliance.com/1228_Working_with_Delegates_in_C#top
reference: http://www.akadia.com/services/dotnet_delegates_and_events.html
Saturday, April 21, 2007
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment