Wednesday 13 April 2011

Dot.Net: Delegates and Actions

Question:
What is the difference between delegates and actions in csharp.


Answer:
Delegates are more general function objects.
You can create a delegate with a signature that you like or need.
An Action in dot.net:
  • is just a short-cut to a delegate that has (zero to four in-arguemnts)
  • the return type is void.
  • supplies behavior - they do something.


Here is an example
TheWriter class can use your method to write something.
In order to pass it your method you must wrap your method inside a delegate.
Here we created a custom delegate CustomAction
public void Test()
{
    TheWriter.UseYourMethodToWrite(Console.WriteLine);
}
public class TheWriter
{
    public delegate void CustomAction(string s);
 
    // This method writes using the custom delegate.
    public static void UseYourMethodToWrite(CustomAction write)
    {
        write("Hello World again");
    }
}

Same example with Action delegate.
public void Test()
{
    TheWriter.UseYourMethodToWrite(Console.WriteLine);
}
public class TheWriter
{
    // This method writes using the custom delegate.
    public static void UseYourMethodToWrite(Action<string> write)
    {
        write("Hello World again");
    }
}

Action is a pre-cooked meal in dot.net programming ...

No comments: