System.Action

Added in .NET 3.5
The Action delegate can be used for methods that accept one or more arguments and do not return a value.

System.Action<string, string> delegate_variable = delegate(string param1, string param2); 
{ //do something }

instead of

delegate void Delegate_Type(string x, string y); 

Delegate_Type delegate_variable delegate(string param1, string param2)
{ // do something }

This delegate can take zero (or more) parameters and must return void.
We have a class that contains a method that we want to call.

public class MyClass 
{
   public void MyMethod() { MessageBox.Show("something"); }
}

Before .NET 3.5 we had to declare the delegate.

public delegate void MyDelegate(); 

public class WithDeclaration
{
   public static void Main()
   {
      MyClass class1 = new MyClass();
      MyDelegate delegate1 = class1.MyMethod;
      delegate1();
   }
}

With .NET 3.5 the custom declaration can now be replaced with the built-in data type new System.Action
There are several ways this could be written.

public class WithoutDeclaration 
{
   public static void Main()
   {
      MyClass class2 = new MyClass();

      System.Action delegate2 = class2.MyMethod;
      System.Action delegate2 = new System.Action(class2.MyMethod);
      delegate2();

      // other ways of writing the same thing
      System.Action delegate3 = delegate() { MessageBox.Show("something"); }
      System.Action delegate3 = new System.Action( () => MessageBox.Show("something"); );
      delegate3();
   }
}


© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext