Understanding Delegates
Delegates are of two types
- Normal delegates
- Generic delegates
1:Normal delegates - These delegates again will fall into three ways of writing it or using it
- Simple delegates
- Anonymous delegates
- Lambda delegates
Simple delegates - these are delegates who are called in a normal way.
- Declare delegate
- Define the method which will match the declared delegate
- Inside the Main method -
- Create object of delegate with method name in its constructor
- Invoke delegate : Pass parameters if any inside the object of delegate similar to method.
- Print the values if needed
Anonymous delegates: These are very similar to normal delegates. The only difference is that the method definition is given directly inside the delegate's constructor with the DELEGATE keyword.
Lambda delegate - This is also similar to simple delegates. The difference is that here we are not creating a delegate object by using the “new” keyword instead we use the object reference of delegate and use lambda operator => to point only to statements of the method without using the return keyword (note there is no method name here). Later invoke delegate reference like a method.
2:Generic Delegates - used to further minimize the code of lambda expression. Here we don't need to declare a delegate declaration
1.Func Delegate - It is a read made delegate with return values i.e Lambda + Func
2. Action Delegate - It is a read made delegate with no return values i.e return void [we are not expecting any return value] i.e Lambda + Action. Action has only input variable and prints or calculates something by taking input variable. This will not return any value.
/*
* predicate is an extension for FUNC. It is used for checking purpose ex: you just want to check the return type is true or false.
* It always return type is boolean.
*Overall if you see, we can make use of FUNC delegate only for returning boolean type.
*There is no need of predicate delegate. So we can avoid Predicate delegate
*/
static void Main(string[] args)
{
Predicate<string> predicateObj = x => x.Length > 5;
List<string> listObj = new List<string>();
listObj.Add("Shiv");
listObj.Add("SureshMarla");
string result = listObj.Find(predicateObj);
Console.WriteLine(result);
Console.ReadLine();
}
Comments
Post a Comment