Sample showing how to use Action<T> in your own code

by sunil ravulapalli /28. September 2013 06:29 /c# /Comments (0)

In the below sample you can see that Action<T> can used to reuse the function Display multiple times. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FuncTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var customers = new List<Customer>();

            customers.Add(new Customer { Id = 1, Name = "aaa"});
            customers.Add(new Customer { Id = 2, Name = "bbb" });
            customers.Add(new Customer { Id = 3, Name = "ccc" });

            //Display Ids
            Action<Customer> action1 = c => Console.WriteLine(c.Id);
            Display(customers, action1);

            //Display Names
            Action<Customer> action2 = c => Console.WriteLine(c.Name);
            Display(customers, action2);

            Console.ReadLine();
        }

        static void Display(List<Customer> customers, Action<Customer> action)
        {
            foreach (var c in customers)
            {
                action.Invoke(c);
            }            
        }
    }

    internal class Customer
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}
blog comments powered by Disqus