Func delegate in c#:-
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<Employee, string> is a delegate that represents a function expecting Employee object as an input parameter and returns a string.
Example:-
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<int, int, string> represents a function that expects 2 int input parameters and returns a string.
Example:-
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<Employee, string> is a delegate that represents a function expecting Employee object as an input parameter and returns a string.
Example:-
using System; using System.Collections.Generic; using System.Linq; class Program { public static void Main() { List listEmployees = new List () { new Employee{ ID = 101, Name = "Santosh kumar singh"}, new Employee{ ID = 102, Name = "Reena kumari"}, new Employee{ ID = 103, Name = "Pramod kumar sah"}, }; // Create a Func delegate Func selector = employee => "Name = " + employee.Name; // Pass the delegate to the Select() LINQ function IEnumerable names = listEmployees.Select(selector); // The above output can be achieved using // lambda expression as shown below // IEnumerable names = // listEmployees.Select(employee => "Name = " + employee.Name); foreach (string name in names) { Console.WriteLine(name); } } public class Employee { public int ID { get; set; } public string Name { get; set; } } }
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<int, int, string> represents a function that expects 2 int input parameters and returns a string.
Example:-
using System; class Program { public static void Main() { Func funcDelegate = (firstNumber, secondNumber) => "Sum = " + (firstNumber + secondNumber).ToString(); string result = funcDelegate(10, 20); Console.WriteLine(result); } }