Generic Delegates

Two generic delegate data types are available.
These have been introduced so you do not have to define your own.
Generic Delegate data types were first introduced in .NET Framework 3.5
You can use delegates to pass a method as a parameter without having to declare a custom delegate.


System.Action

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();
   }
}


System.Func





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