C# Delegates and Events—Declaring and using delegates
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
| CSharp-Online.NET:Articles |
| C# Articles |
| edit |
Declaring and using delegates
You declare a delegate in a class or namespace using the delegate keyword and by specifying the signature of the method it will call. The following line declares a delegate named GreetingDelegate which will reference a method that returns void and accepts a string as the argument.
delegate void GreetingDelegate(string s);
Now that we have declared the GreetingDelegate, we can instantiate it to encapsulate a method of that signature. Then, we can invoke the method through the delegate, just as if we invoked the method itself.
The next code sample creates an instance of GreetingDelegate and uses it to invoke the SendGreeting method.
class DelegateDemo1 { static void Main(string[] args) { GreetingDelegate gd = new GreetingDelegate(SendGreeting); gd("Hello"); } static void SendGreeting(string s) { Console.WriteLine(s); } }
The DelegateDemo1 class shown above contains a static method named SendGreeting which has the same signature as the GreetingDelegate defined earlier. The Main method instantiates the GreetingDelegate, passing the SendGreeting method as argument. Next, Main invokes the SendingGreeting method through the delegate instance, passing the string “Hello”.
Delegates only depend on the signature of the method, not on the class or object containing the method. Although the SendGreeting method above was declared as static, this is not a requirement. A delegate can reference an instance method as well. The next example uses the same GreetingDelegate defined earlier to invoke an instance method.
class Greeting { public void SendGreeting(string s) { Console.WriteLine(s); } } class DelegateDemo1 { static void Main(string[] args) { Greeting gr = new Greeting(); GreetingDelegate gd = new GreetingDelegate(gr.SendGreeting); gd ("Hello"); } }
This example defines a Greeting class that contains a single method named SendGreeting. Because its signature matches that of the GreetingDelegate, the method can be invoked through our delegate.
In this example, the Main method first instantiates the Greeting class. Then, it creates an instance of GreetingDelegate, passing the Greeting object’s SendGreeting method as argument. Finally, Main calls the object’s SendGreeting method by invoking the delegate.
|

