HI WELCOME TO Sirees

Func delegate in c#

Leave a Comment
we will discuss, the purpose of Func<T, TResult> delegate in c# with an example.

What is Func<T, TResult> in C#?
In simple terms, Func<T, TResult> is just a generic delegate. Depending on the requirement, the type parameters (T and TResult) can be replaced with the corresponding type arguments. 



For example, Func<Employeestring> is a delegate that represents a function expecting Employee object as an input parameter and returns a string.

Program used in the demo:
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    public static void Main()
    {
        List<Employee> listEmployees = new List<Employee>()
        {
            new EmployeeID = 101Name = "Mark"},
            new EmployeeID = 102Name = "John"},
            new EmployeeID = 103Name = "Mary"},
        };

        // Create a Func delegate
        Func<Employeestring> selector =
            employee => "Name = " + employee.Name;
        // Pass the delegate to the Select() LINQ function
        IEnumerable<string> names = listEmployees.Select(selector);

        // The above output can be achieved using
        // lambda expression as shown below
        // IEnumerable<string> names =
        // listEmployees.Select(employee => "Name = " + employee.Name);

        foreach (string name in names)
        {
            Console.WriteLine(name);
        }
    }

    public class Employee
    {
        public int ID { getset; }
        public string Name { getset; }
    }
}

What is the difference between Func delegate and lambda expression?
They're the same, just two different ways to write the same thing. The lambda syntax is newer, more concise and easy to write.

What if I have to pass two or more input parameters?
As of this recording there are 17 overloaded versions of Func, which enables us to pass variable number and type of input parameters. In the example below, Func<intintstring> represents a function that expects 2 int input parameters and returns a string.

using System;
class Program
{
    public static void Main()
    {
        Func<intintstring> funcDelegate = (firstNumbersecondNumber=>
            "Sum = " + (firstNumber + secondNumber).ToString();

        string result = funcDelegate(1020);
        Console.WriteLine(result);
    }
}

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.