What is Func, how and when it can be used, examples

What is func in c# how to use func in c# what are the different parameters for func c# func return void func c# multiple parameters func in c# example func c# parameter func c# delegate func c# tutorial

Func is a predefined delegate. .Net have 17 Func delegates with different parameters from 1 to 17. Every Func delete last parameter is return type says TResult. It encapsulte a method which have zero (0) to 16 parameters, except the last one, rest of the parameters are function input parameter.

Let's see how it is defined internally

public delegate TResult Func<out TResult>();
public delegate TResult Func<in T, out TResult>(T arg);
public delegate TResult Func<in T1, in T2, out TResult>(T1 arg1, T2 arg2);
public delegate TResult Func<in T1, in T2, in T3, out TResult>(T1 arg1, T2 arg2, T3 arg3);
public delegate TResult Func<in T1, in T2, ...., in T16, out TResult>(T1 arg1, T2 arg2, ..., T16 arg16);

Now we have a clear picture how it is defined by Microsoft, check it yourself

Why we need to know this?

There are many functions which accept Func as parameter, if we don't know about Func delegate we cannot use them property. There are many functions which we are using every day but we don't know that they accept parameter as Func, let's see some of the examples to understand it better

Let's see it with an array of integers and apply where, order by on it

 int[] arr = {1, 3, 2, 4, 6, 5, 7, 9, 8, 10 };    

 var evenItems = arr.Where(x => x % 2 == 0);    

 var sortedArray= arr.OrderBy(x => x);

Where and OrderBy are functions, do you know what are the parameter type they accept, it is Func

.Where(Func<int, bool> predicate)   
.OrderBy(Func<int, int> keySelector)

To understand it, we need to use our 10th class Math function writing style, let's see

 f(x) => x + 10  // Add 10 to x
 g(x) => x * x   // Square of x
 h(x) => x % 2 == 0
 j(x,y) => x == y // Equality test

Now let's take our Where and h`(x) examples together

 .Where(Func<int, bool> predicate)
 h(x) => x % 2 == 0

h(x) accept one parameter as integers and return true if devisible by 2 otherwise false.

In the same way our Where function accept a Func with two parameter an integer(input) and bool(output).

Use Func for our math examples

We are going to write our above Math function into Func format

Func<int, int> f = x => x + 10;             // f(x)
Func<int, int> g = x => x * 10;             // g(x)
Func<int, bool> h = x => x % 2 == 0;        // h(x)
Func<int, int, bool> j = (x, y) => x == y;  // f(x)

Func usage and examples

Let's say we have to write a function which can accept any two type of input parameters and return any type by adding them, where we will end? We will be writing separate method for short, int, long, single, double, string ... and many more. Can we use Func delegate here, of course, let's see it one by one

To add two integers and return integer

Func<int, int, int> myAddition = (x, y) => x + y;
Console.WriteLine(myAddition(10, 20));

To add two string and return an string

Func<String, String, String> myStringAddition = (x, y) => x + y;
Console.WriteLine(myStringAddition("Hellow ", "World!"));

To add two single and return a double

Func<Single, Single, Double> mySingleAddition = (x, y) => (Double)(x + y);
Console.WriteLine(mySingleAddition(10.10f, 15.25f));

If I ask to write a function to check the pythagorous theoram where will you end, let's see without Func first

public static bool IsPythagoreanValuea(int length, int height, int hypotenuse)
    var a = length * length;
    var b = height * height;
    var ab = a + b;
    var c = hypotenuse * hypotenuse;
    if (ab == c)
        return true;
        return false;

The same function we can write with Func delegage like this:

Func<int, int, int, bool> IsPythagoreanValue = (x, y, z) => x * x + y * y == z * z;
Console.WriteLine(IsPythagoreanValue(4, 3, 5));

Is not it easy and simple to use.

Func with void return method

As we discuss Func always use last parameter as return type, if a function don't accept any parameter and return something then we use Func<RetrunType>. So it is create Func cannot be used for a function with return type void rather we can use Action, see the example

Say we have some function like this:

public static void SomeFunction(int i, string str) 
  // Some code here

Our SomeFunction returns void so we can use Action:

var action = new Action<int, string>(SomeFunction);
    Action<int, string> action = SomeFunction;
Ali Adravi Having 13+ years of experience in Microsoft Technologies (C#, ASP.Net, MVC and SQL Server). Worked with Metaoption LLC, for more than 9 years and still with the same company. Always ready to learn new technologies and tricks.
  • func
  • c#
By Ali Adravi On 05 Jun, 16  Viewed: 3,493

Other blogs you may like

How to Manage the Backend Functionality of Your Magento Store?

Helper contains the necessary functions for you; you can call in a helper from anywhere. An example of helper is as below $helper = Mage::helper('monhelper'); The call can be related to $helper = Mage::helper('monhelper/data'); **Let's create a helper file** You will need to... By Deepa Ranganathan   On 17 Jul 2015  Viewed: 226

default value for different data type in C#

In C# there are different data type and they use some default value when we declare a variable. When we define a variable of type int or Int32 say int score; so what is the value of score, will it be null or zero, in the same way if we create a variable of type string/String what value it holds... By Ali Adravi   On 27 Mar 2013  Viewed: 2,623

enum in C# and conversion

An enumeration type (also known an enumeration or an enum) provides an efficient way to define a set of named integral constants that may be assigned to a variable to make programming clear, understandable and manageable. There are ways of using, like how to use enum in switch and case statement,... By Hamden   On 27 Mar 2013  Viewed: 4,586

Dynamic vs var in C# with example

When we have var which dynamically holds any type or value so why we need dynamic type, what are the differences and situations where we can use dynamic rather than var, there were some question in my mind so I explored more which I want to share here. There are two things, static type and... By Nathan Armour   On 26 Mar 2013  Viewed: 3,223

Array in C# - single, multiple and jagged array

An array can be initialized in several ways, it can store a single value or series of values, every element must be set of same type, C# supports single-dimensional arrays, multidimensional arrays (also call rectangular array) and array-of-arrays (referred jagged arrays), let’s discuss features of... By Ali Adravi   On 24 Mar 2013  Viewed: 4,409