C# Action Delegate

action delegate in c#

In last post about generics mentioned about Action delegate. Action is a type of delegates that takes 0 to 16 arguments and returns no value. It’s similar to void method. It’s part of System.collection.generic. Actions can point  to anonymous function in form of lambda expression. Let’s take a look at example.

using System;

class Program
{
    static void Main()
    {
	Action example = () => Console.WriteLine("example method invoked");
	example.Invoke();
    }
}

In this example, Action takes no parameters and return a method that prints string to the console.

We can add input parameter to this example and pass the string that we want to print.

using System;

class Program
{
   static void Main()
   {
     Action<string> example =
     (string str) => Console.WriteLine(str);
     example.Invoke("example method invoked");
     Console.ReadLine();
   }
}

In next post I’ll cover the topic of Func<T1,T2> which is Delegate that returns a value. Stay Awesome!

 

Events

In last post we discussed implementation of Delegates using one simple example. If you haven’t read it already i strongly encourage you to do so before moving to today’s  topic. Today we will take closer look at events. In last example we created one main class with all methods inside it. Today we will learn how to communicate between different classes, by subscribing to the event.

Lets create our first class called publisher, here we will crate our event and we will publish it. This way we will be able to invoke methods in other classes.

using System;

//We are using the delegates we described in last post
public delegate void EventHandler();

class Program
{
 //New event based on the delegate above called newEvent
    public static event EventHandler newEvent;
// Class constructor
public Program(){
//You can put something here
} 
public void AddSubscribers()
    {
	// Add event handlers to our event
	newEvent += new EventHandler(Command1);
	newEvent += new EventHandler(Command2);
	
    }

    static void Command1()
    {
	Console.WriteLine("Event executed");
    }

    static void Command2()
    {
	Console.WriteLine("Warning!");
    }

    public void InvokeEvent(){
    //We are using this to invoke the event
   newEvent.Invoke();
}
}

this is class of our program here we can subscribe new methods to our event and the most important, call our invoke method.

Now lets create second class so we can see how event behave with other classes.

  Public class MainClass{  

public static void Main(){

    Program newProg= new Program();
   //Now we can add our subscribers from Program class
   newProg.AddSubscribers();

    //Or add subscriber from this class
    Subscribe(newProg);

    //Here we finally invoke our event
    newProg.InvokeEent()

    }
    //Here we can subscribe to event of different class
    public Subscribe(Program newProgram){
     newProgram.newEvent += new EventHandler(Command3)
    }
    static void Command3()
    {
        Console.WriteLine("Great!");
    }
}

In this example we can see how we can use event to crate connections between different classes. We can use it in in many different cases, in games development we can crate event calling subscribers when unit is created or destroyed, this way we can easy handle methods spreader between all classes. In next entry I’ll cover lambda expressions, they can help you write more readable code faster. Stay Awesome!

 

 

Delegates

Have  you ever thought about using method as a parameter? Having ability to invoke multiple methods with one command?  Delegates can make those ideas reality .

All delegates are implicitly derived from the System.Delegate class. Here is basic structure of delegates:

delegate <return type> <delegate-name> <parameter list>

Delegate syntax is very similar to the method syntax, i takes list of parameters and have return type. Important thing to consider is that all methods passed to delegate must have the same structure, number and type of parameters and return type. Lets take a look at example:

private delegate int Calculator(int n);
public static int AddNum(int p)

We can see that both methods have the same return types and takes the same parameters.

Let’s move on to the Practical example.

using System;

// Here is our delegate takes int and returns int
private delegate int Calculator(int n);

   class Calculator
   {
      //Initial value
      static int num = 5;

      //Creating methods
      //All methods must have the same structure 
      public static int AddNum(int p)
      {
         num += p;
         return num;
      }
      public static int MultNum(int q)
      {
         num *= q;
         return num;
      }
      public static int SubctNum(int q)
      {
         num -= q;
         return num;
      }
      public static int getNum()
      {
         return num;
      }
      //Calling the main function
      static void Main(string[] args)
      {
         //create delegate instances
         Calculator c1 = new Calculator(AddNum);
         Calculator c2 = new Calculator(MultNum);
         Calculator c3 = new Calculator(SubctNum)

         //We can connect multiple delegates to execute them together 
         c1 += c2;
         c1 += c3;
         
         //We can also delete reference
         c -= c3; 
         
         // Lets call our delegate
         c(2);

         Console.WriteLine("Value of Num: {0}", getNum());
         Console.ReadKey();
      }
   }

Try this on your compiler see the result.

We just created simple Calculator application that can perform multiple operations with just one call of delegate. This is just the beginning of endless possibilities. Methods can be simplified to shorter versions aka “lambda expressions”.  Try to remember “+=” operator, we will come back to this while we will talk about events, but this is subject for another post. Stay Awesome.