Func Delegate uses in C#

Delegate keyword is magical word in c# , it acts as function pointer in C#.Unfortunately I am not explaining about delegate but a type of delegate which is func delegate.

Func<T, TResult> is nothing but a predefined generic delegate which has T is type of the parameter of the method that this delegate encapsulates and TResult is out type of the return value of the method that this delegate encapsulates.

Both T and TResult are generic in nature meaning it can be replaced by different types according to requirement.

Func<Customer,string> is delegate which has input parameter as customer class and which is retuning output of string type.

By the example below we are trying to use func delegate to give customer as input and form a string to return first name using lambda expression.

public class Customer
{

    public
int ID { get; set; }
    public
string FirstName { get; set; }
}

List
<Customer> customers=new List<Customer>()
{

    new
Customer{ID=1,FirstName="Abhishek"},
    new
Customer{ID=2,FirstName="Ram"},
    new
Customer{ID=3,FirstName="Paul"}
};

Func
<Customer, string> del = Cust => "First Name " + Cust.FirstName;
IEnumerable
<String> names = customers.Select(del);
foreach
(String s in names)
{

    Console
.WriteLine(s);
}

Func<Customer, string> is a delegate which is returning first name of type string as output.

Func<T, TResult> delegate, you do not have to explicitly define a delegate that encapsulates a method with a single parameter

We can use this delegate to represent a method that can be passed as a parameter without explicitly declaring a custom delegate.

Ebook Download
View all
Learn
View all