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!