Func in C#

Introduction

.Net has provided three predefined delegates,

  1. Func
  2. Action
  3. Predicate

In this article, we are going to discuss about func, the predefinde generic delegate in C#. To get a better understanding of func, first, we should have a basic understanding of delegate so we will take a basic understanding of delegate and then jump into func.

 Here I will try to touch few important points of delegates using a simple example. Please note that I am not going to discuss delegates in the depth here.

The first obvious question is,

What is a delegate?

A delegate is a type-safe function pointer. A delegate is a reference type that can hold the reference of the method.

The namespace of delegate is System.Delegate and all delegates implicitly derived from this.

Let's try to understand the simple example of delegate,

using System;

namespace FuncTest
{
    class Program
    {
        public delegate int MathDelegate(int a, int b);
        static void Main(string[] args)
        {
            MathDelegate mathDelegate;

            mathDelegate = Add;
            Console.WriteLine("Sum of Two Numbers :" + mathDelegate(10,5));

            mathDelegate = Sub;
            Console.WriteLine("Substraction of Two Numbers :" + mathDelegate(10, 5));

            Console.ReadLine();

            static int Add(int a, int b)
            {
                return a + b;
            }

            static int Sub(int a, int b)
            {
                return a - b;
            }
        }
    }
}

In the above example,

  1. We have declared delegate.
  2. Created two methods Add and Sub.
  3. Assign method to delegate.
  4. Invoke methods.

Output

I hope now we all have a good understanding of the delegates. Let's move on to the func and will use the same example for func.

What is Func?

In the simplest words, func is a generic delegate introduced with .Net 3.5.

Microsoft has provided func - a in-built delegate in the System namespace.

func can be used with a delegate that has returned value.

How to declare Func Delegate?

We should know in which namespace and assembly, newly introduced functionality is available. 

func is included in the 

NameSpace : system 

Assembly : System.Runtime.dll.

We can use the below func syntax in c#,

Syntax 

Func <T, TResult> 

T – Type of Input parameters.

TResult – Type of return parameters.

func has 17 overloaded methods means it can have 0 to 16 input parameters and one output parameter.

Let's see the below sample overloaded examples,

Zero parameter example

public delegate TResult Func<TResult>

One Parameter example

Public delegate TResult Func<T, TResult>

16 Parameters example

Func <T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,TResult>

Please note that func does not allow ref and out parameters. func can be used with anonymous and lambda expressions.

Now we have a basic understanding of func delegate. Let's try to understand func with a simple Math example. I am going to Add two numbers, subtract, and multiply 2 numbers.

A simple example of func delegate

using System;

namespace FuncTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<int, int, int> funcMath;
            funcMath    = Add;
            Console.WriteLine(funcMath(15,5));

            funcMath = Sub;
            Console.WriteLine(funcMath(15, 5));
            Console.ReadLine();

        }
        public static int Add(int a,int b)
        {
            return a + b;
        }
        public static int Sub(int a, int b)
        {
            return a - b;
        }
    }
}

In the above example, we have

  • Two simple static methods – Add and Sub
  • We have func delegate called “funcMath” that takes two int as input parameters and return int as output.   
  Func <int, int, int> funcMath;

We have assigned both the method to func.

eg

funcMath = Add;

funcMath = Sub;

We have passed int values (15,5) into func and called the function.

Console.WriteLine(funcMath(15,5));

Once you execute the above example, you will see the below output. 

Output

As we discussed earlier that func can be used with Lambda and anonymous. Let's try to use func with Lambda expression. 

Let's assume that we have removed add and sub methods from the above example and replaced them with lambda expressions.

Func with lambda

using System;

namespace FuncTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<int, int, int>  funcMath = (n1, n2) => n1 + n2;
            Console.WriteLine(funcMath(15,5));

            funcMath = (n1, n2) => n1 - n2;
            Console.WriteLine(funcMath(15, 5));
            Console.ReadLine();
        }
    }
}

In the above example, we have removed Add and Sub and replaced that function with Lambda express and compare the output.

Output

We got the same output, so then an obvious question comes in mind what is the difference between func and Lambda expression?

What is different between Func and Lambda expressions?

To get a better understanding of the differences, Let's see the below examples,

using System;
using System.Collections.Generic;
using System.Linq;

namespace FuncTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Member[] member = {
              new Member{ID = 1,Name = "Kirtesh",City = "Vadodara"} ,
                new Member{ID=2,Name="Nitya",City="Surat"},
                new Member{ID=3,Name="Dilip",City="Dabhoi"},
            };
            Func<Member, bool> funcMember = m => m.ID == 1;
            var result = member.Where(funcMember);
            foreach (var item in result)
            {
                Console.WriteLine(item.Name);
            }

        }
     }
}

In the above example,

  1. We have a members array.
  2. We need to find a member name whose id is 1
  3. We have created func and pass as an argument in the where condition.

Output

Let's try the below code,

using System;
using System.Collections.Generic;
using System.Linq;

namespace FuncTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Member[] member = {
              new Member{ID = 1,Name = "Kirtesh",City = "Vadodara"} ,
                new Member{ID=2,Name="Nitya",City="Surat"},
                new Member{ID=3,Name="Dilip",City="Dabhoi"},
            };
             var result = member.Where(m => m.ID == 1);
            foreach (var item in result)
            {
                Console.WriteLine(item.Name);
            }

        }
     }
}

In the above example,

  1. We have created Members Array
  2. Need to find out Member whose id is 1
  3. Use Lambda expression instead of func.

Output

You notice that we have received the same output.

If we can achieve the same result with lambda then the obvious question comes to mind what is the difference between func and lambda? 

The answer is: Both(func and Lambda) are same. Lambada expression is a newer easy way to write the same code.

Let's discuss one more example to get a better understanding,

Func with LINQ

using System;
using System.Collections.Generic;
using System.Linq;

namespace FuncTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<string, bool> hasLength = str => str.Length > 4;
          
            string[] countries = { "India", "United Kingdom", "US", "China", "Pakistan", "Afghanistan","Rush" };
            IEnumerable<string> country= countries.Where(hasLength);
            foreach (var item in country)
            {
                Console.WriteLine(item);
            }
            Console.ReadLine();
        }
     }
}

Output

That’s all in this article. Hope you like and enjoy this article.


Similar Articles