What is delegate in C#?Delegates are just like as a class that can be instantiated and work like a pointer which points to function.
Signature of a delegate is the Union of its return type and input parameter. So the function having same signature like delegate can be assigned to the reference of a delegate.
Syntax:public delegate string Agent(int id, string name);Here return type is string and input parameter is int & string.
So the signature is union of return Type and its Input Parameter.
Signature = string + (int, string).
So all the function having same signature like a delegate can be assigned to the reference of delegate.
First Approach for Creating Instance of delegate
Agent agnt;
Second Approach for Creating Instance of delegate
Agent agnt= new Agent();
IF we are having a function with same signature like delegate as below
public static string flatOnRent(int Id,string name)
{
string rtrnString="";
if (name == "Mulund")
{
rtrnString= "Flats Available For Rent in " + name.ToString();
}
return rtrnString;
}
And we want to assign this function to delegate than follow one of the below step.
Agent agnt= flatOnRent;
OR
Agent agnt= new Agent(flatOnRent);
Here we can see delegate agnt is now pointing to function flatOnRent.
Sample Code:
Decription of Code:
There was a agent who used to provide house on rent and for that he was having a fuction called ProcessRequest. After Some Time he thought to start selling of house beside providing the rent so he had modified function ProcessRequest() , but after few of months one of his friend suggest him to invest money in purchasing of flats but at this time Agent didnot want to modify the existing fuction ProcessRequest() , he was looking for a different approach where he could add more and more features in his business without altering existing function ProcessRequest(). he decided to use delegates where the requirement is supplied to delegate instead of passing it directly to ProcessRequest() method.
The Method ProcessRequest() is modified where it is accepting delegate(Agent) refernce
public static void processRequest(string[] strCity,Agent agnt)
{
foreach (string str in strCity){Console.WriteLine(agnt(str).ToString());}
}
Rest of the Steps are very simple
1. Declare the delegate
public delegate string Agent(string name);
2. Declare the fuctions with same signature like delegate
public static string flatOnRent(string name)
{
string rtrnString="";
if (name == "Mulund"){rtrnString= "Flats Available For Rent in " + name.ToString(); }
return rtrnString;
}
public static string buyFlat(string name)
{
string rtrnString="";
if (name == "Thane"){rtrnString="Flats Available in " + name.ToString() + " to Pucrchase";}
return rtrnString;
}
3. Now Call the ProcessRequest Method and pass the fuction which you want to assign the delegate refernce.
//1. Point delegate to flatOnRent method.
processRequest(strCity, flatOnRent);
//2. Point delegate to buyFlat method.
processRequest(strCity, buyFlat);
What is Anonoymous Method in C#?
Anonymous methods are just like as normal instance function without having a Name.It is little bit confusing because as we know fuctions are Named block of Code but Anonymous methods are opposite of that.So we can define the Anonoymous method as a shorthand for a delegate where we assign directly the body of function instead of declaring the function seperately.
we will modify our delegate code slightly in this time we will not declare the function flatOnRent and buyFlat seperately.We will directly assign the body of function to the refernce of delegate.
Syntax is very simple: delegate(inputParameter ip){body of the function;}
Sample Code:Description:
We can see from the above code that it becomes qiute compact as compare to delegate code just because of Anonymous method and result is same.
Note the below points
1. Methods flatOnRent() and buyFlat() are removed from the code
2. processRequest() is now accepting the anonymous method, basically it is still pointing to the delegate Agent thats why the delegate key word is used in the syntax.
Now the code
processRequest(strCity, flatOnRent);
processRequest(strCity, buyFlat);
is modified and it looks like as below
1. processRequest(strCity,delegate(string name){string rtrnString="";if(name=="Mulund"){rtrnString="Flats Available For Rent in "+name.ToString();}return rtrnString;});
2. processRequest(strCity,delegate(string name){string rtrnString="";if(name=="Thane"){rtrnString="Flats Available in "+name.ToString()+"to Pucrchase";}return rtrnString;});
What is Func<> function in C#?
Microsoft has created a generic delegate for us which is known as Func<>.It is overloaded delegate, we can create combination of signatures with this Func<> delegate.
Syntax:
Func<inputParameters,..........,Last Parameter is OutPutType> objFunc;
A Good news for us is that we neednot have to declare delegate seperately in our Code.
So our Previous Code became more compact.
Comapct Delegate Code:
What is Lambda Expressions in LINQ?
Lambda expressions are again shorthand for Anonymous Methods.Lambda expression are still pointing to delegate like Anonymous method.It could be more clear by below code statement.
In the previous code we have just eliminated the delegate key word and added a seperator i.e. => between the input parameter and body.very simple isn't it?
processRequest(strCity,(string name)=>{string rtrnString="";if(name=="Mulund"){rtrnString="Flats Available For Rent in "+name.ToString();}return rtrnString;});
Now at this stage you will be not shocked by seeing this odd syntax of Lambda because we have seen the evaluation of Lambda expression from the base.
we will continue to learn this Method Syntax of LINQ.
Modified Sample Code:
Alternate Sample Code with same output:
Final OutPut:
This output is same for all the code written from delegate to Lambda Expression