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!

 

Author: indiedevart

Indie Games Developer

One thought on “C# Action Delegate”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s