Delegate in .NET is a type which can refer to a method.So if we have a delegate type declared as
delegate int tempDelegate(int a,int b);
then the above delegate can point to a method which accepts two integer arguments and returns an integer type
tempDelegate objDelegate=Add; int sum=objDelegate(1,2); public int Add(int a,int b) { return a+b; }
There are few common signatures of delegates used commonly in the applications.For example many times we need to declare a delegate
which accepts integer arguments and returns integer value.
Instead of declaring delegates for every input and output types .NET framework provides some generic delegates.Action,Func and Predicate in .NET can be used to refer to commonly used methods instead of declaring a new delegate type.
Action<TParameter> delegate points to a method which accepts parameters but does not return any value.
In the following example we have declared an Action<T> delegate which accepts string argument and return void.
Action<string> displayObj = Display; displayObj("Hello!"); public void DisplayMessage(string message) { Console.WriteLine(message); }
Func<TParameter,TOutput> delegate points to a method which accepts parameters and also returns a value.In the following example we have declared a Func<T> object which accepts two integer arguments and returns an integer.
Func<int, int,int> addObj = Add; int sum=addObj(2, 4);
Predicate<TParameter> delegate points to a method which accepts parameter and always returns a boolean value.In the following example we have declared Predicate<T> which accepts a Person type object and returns a bool value.
Predicate<Person> personObj = IsPersonAdult; public bool CheckPersonsAge(Person person) { return person.Age < 18; }
Leave a Reply