Tuesday, 27 October 2020

C# - Action<>, Func<>, Predicate<>

How to work with Action, Func, and Predicate delegates in C#

Programming Action delegates in C#

static void Main(string[] args)
{
    Action<string> action = new Action<string>(Display);
    action("Hello!!!");
    Console.Read();
}
static void Display(string message)
{
    Console.WriteLine(message);
}

Programming Func delegates in C#

static void Main(string[] args)
{
    Func<int, double> func = new Func<int, double>(CalculateHra);
    Console.WriteLine(func(50000));
    Console.Read();
}
static double CalculateHra(int basic)
{
    return (double)(basic * .4);
}

 

Programming Predicate delegates in C#

class Customer
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Country { get; set; }
}
static void Main(string[] args)
{
    List<Customer> custList = new List<Customer>();
    custList.Add(new Customer { Id = 1, FirstName = "Joydip", LastName = "Kanjilal",
                               State = "Telengana", City = "Hyderabad",
                               Address = "Begumpet", Country = "India" });
    custList.Add(new Customer { Id = 2, FirstName = "Steve", LastName = "Jones",
                               State = "OA", City = "New York",
                               Address = "Lake Avenue", Country = "US" });
   
    Predicate<Customer> hydCustomers = x => x.Id == 1;
    Customer customer = custList.Find(hydCustomers);
    Console.WriteLine(customer.FirstName);
 
    Console.Read();
}


No comments:

Post a Comment