C# Generic Delegates Func, Action, and Predicate

Do you know about delegates? Please learn about basics of delegates before starting it article this will help you to understand better.

What are Delegates?
As delegates sounds like something big. But believe me, it is very simple. Delegates are pointer to function. It is used for implementing event and call back method.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace ConsoleApplication3
{
public delegate int MyDelegate(int x,int y);
public class DelegateClass
{
public static int Add(int x, int y)
{
return x+y;
}
public static int GetValue(int x)
{
return (10+x);
}
public static void ShowValue(int x)
{
Console.WriteLine("Value" + x);
}
public static int GetResult()
{
int x = 30;
int y = 20;
return x*y;
}
public static void ShowEmploye(int age,String name)
{
Console.WriteLine("My Name is" + name);
Console.WriteLine("My age is " + age);
}
public static void ShowMessage(String msg)
{
Console.WriteLine(msg);
}
public static bool IsNumeric(object Expression)
{
double retNum;
bool isNum = Double.TryParse(Convert.ToString(Expression), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum);
return isNum;
}
}
public class MainClass
{
public static void Main()
{
//Assign method to delegates
MyDelegate delAdd = DelegateClass.Add;
//Call add method using custome delegates
int sum = delAdd(1,2);
Console.WriteLine(sum);
//You can't call other method which is having only one input parameter
MyDelegate del = DelegateClass.GetValue; //Compilation error since signature of delegates not matching
}
}
}

Func, Action and Predicate are define in C# 3.0 and these are generic inbuilt delegates. The above steps are not required, if you use these delegates.

Func Delegate:
Func is generic delegate present in System namespace. It takes one or more inputparameters and returns one out parameter. The last parameter is consider as return value.
Func delegate type can include 0 to 16 input parameters of different types. It must have one return type. So return type is mandatory but input parameter is not.

Example1: Func delegate with two input parameters and one return value.
Func func1 = DelegateClass.Add;
int value = func1(10, 20);
TParameter = 10,20;
TOutput = value = 30;

Example2: Func delegate with one input parameter and one return value.
Func func2 = DelegateClass.GetValue;
int values = func2(30);
TParameter = 30
TOutput = 40;

Example3: Func delegate with zero input parameter and one return value.
Func func3 = DelegateClass.GetResult;
int resultMulti = func3();
TParameter = Nothing
TOutput = 600;

Func with Anonymous methods:
Func func4= delegate(int x,int y){ return (x+y); };
int result = func4(2,3);

Func with Lambda expression:
Func func5= (int x,int y) => { return (x+y); };
int xx = func4(2,3);

Action Delegate:
Action is generic delegate present in System namespace. It takes one or more inputparameters and returns nothing.
So it does not return any value.

Example1: Action delegate with two input parameters.
Action action1=DelegateClass.ShowEmploye;
action1(30,”Rajesh”);
TParameter = 30,Rajesh;
TOutput = Not available (No return value)

Example2: Action delegate with one input parameter.
Action action2=DelegateClass.ShowMessage;
action2(“Rajesh”);
TParameter = “Rajesh”
TOutput = Not available

Action delegate with Anonymous methods:
Action action = delegate(String msg)
{
Console.WriteLine(msg);
};
action(“rajesh”);

Action delegate with Lambda expression:
Action action= (msg)=>{Console.WriteLine(msg)};
action(“Rajesh”);

Predicate Delegate:
Predicate delegate is also inbuilt generic delegate and is present in System namespace.
It is used to verify certain criteria of method and returns output as Boolean, either True or False.
Predicate can be used with method, anonymous and lambda expression.

Example1: Check String value is number using Predicate delegates.
Predicate predicate = DelegateClass.IsNumeric;
bool number = predicate(“1234”);

Example1: Predicate delegate using Anonymous method.
Predicate predicate = delegate(string str)
{
double retNum;
bool isNum = Double.TryParse(Convert.ToString(str), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum);
return isNum;
};
bool found = predicate(“12232”);

Example1: Predicate delegate using lambda expression.
Predicate predicate = (str) =>
{
double retNum;
bool isNum = Double.TryParse(Convert.ToString(str), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum);
return isNum;
};
bool found = predicate(“12232”);

Conclusion:

  • Func, Action and Predicate are generic inbuilt delegates present in System namespace.
  • All three can be used with method, anonymous method and lambda expression.
  • Func can contains 0 to 16 input parameters and must have one return type.
  • Action can contains 1 to 16 input parameters and does not have any return type.
  • Predicate delegate should satisfy some criteria of method and must have one input parameter and one Boolean return type either true or false.
  • Input parameters of custom delegates is fixed but Func and Actions input parameter is variable from 0 to 16 and 1 to 16 respectively.

14 Comments

  1. Thanks ffоr one’s marvelous posting! I ceгtainly enjoyed reading it,
    yоu can be a great author.I will make certain to bookmark yor Ьlog and wilⅼ eventually come back freom now on. I
    want to encolurage yyou to uⅼtimatеly cоntinue your great job, have a nice weekend!

  2. Writе more, thats all I have to say. Literallʏ, it
    seеms as though you relied on the video to makе your point.
    You clearly knoᴡ what yoսre talking about, whʏ thrߋw awaʏ your intеlligence oon just posting viddos to
    your wеblog when үou could be giving us something іnformative to гead?

  3. Hey I know thiѕ is off topiс but I was wondering if you knew of any widgets I coᥙⅼd add to my blog that
    aut᧐matically tweet my newest twitter updates. I’ve Ƅеen lloking for ɑ plᥙg-іn like this for quite
    some timee and was hoping maybe you would have some experfience with
    sometһing like this. Pleaѕe ⅼet me know if you run intо anything.
    I truuly enjoy reading your blog and I look forward to your new updates.

  4. Good day! Thіs post couldn’t be written any better!
    Reading this post remіnds me of my previous rooom mate!
    He alwayѕ kept talking about this. I will forqard this post to him.
    Fairly certain hhe will have a goοd гead.

    Thank you for sharing!

  5. Нmm it looks like your blog ate my first comment (it was super long) so Ӏ guess I’ll just sum iit
    up wһat I submitted and say, I’m thoroughly enjoying your blog.
    I as well am an aspiring bloɡ bloggger but I’m
    stiⅼl new to the whole thing. Do yⲟu hav any ѕuggestions
    foг beginnеr blog writers? I’d genuinely appreciаte it.

  6. Eхcelklent post. I waѕ chhecking constanty this blog
    and I am inspired! Very helpful information particularly thе
    ultimate part 🙂 I care for such infоrmɑtion a lot.
    I wass seeking thiѕ particular info for a very long time.
    Thanks and good luck.

  7. I know this if off topic but І’m looking іnt᧐ stаrtіng
    my own weblog and was curiouѕ what all is needred to get set
    up? I’m assuming having a blog like yours would cost a pretty
    penny? I’m not very web smart soο I’m not 100% sսre. Any recommendations or adνice wouⅼd
    be greatly apprеciаted. Thank you

  8. I’m not suгe whеre you are getting youг informatiօn, but
    good topic. I needs tto spend some time learning more
    or understanding more. Thanks fοr fantastikc informɑtion I was looking for thiѕ information for my
    mission.

Leave a Reply

Your email address will not be published.


*