Click here to Skip to main content
Click here to Skip to main content

Tagged as

Go to top

Uses of Func in C#

, 11 May 2014
Rate this:
Please Sign up or sign in to vote.
Uses of Func in C#

What is Func?

Func in short is parameterized delegate. In C#, a delegate instance points towards a method. When a caller invokes the delegate, it calls its target method. This way, the caller is not invoking the target method rather invoking the delegate which can call the target method. We do it because it creates an abstraction on invoking the target method. We of course always can invoke a method directly but decoupling of the client and target method is sometimes a need or gives us more flexibility to make things clean and simple.

We can use Func delegate to represent a method that can be passed as a parameter without explicitly declaring a custom delegate.

Why I said it's a parameterized delegate:

delegate TResult Func <out TResult> ();
delegate TResult Func <in T, out TResult> (T arg);

delegate TResult Func <in T1, in T2, out TResult> (T1 arg1, T2 arg2);

... and so on, up to T16   

The Problem

To understand use of Func, we must understand what problems it can solve. Let's say we have an int array here.

IEnumerable<int> numbers = new[] {3, 4, 7, 1, 8, 10, 21, 5, 9, 11, 14, 19};

It's a simple array. If we want to print the numbers which are greater than 10, we will write a method like below. We will send the array as parameter and will get another array which will contain the numbers that are greater than 10.

public IEnumerable<int> GetGreaterThanTen(IEnumerable<int> numbers)
    foreach (int number in numbers)
        if (number > 10)
            yield return number;
…and then if we want to print the numbers which will have result less than 1 after divided by 5, we will write a method:
public IEnumerable<int> GetGreterThanOneAfterDevidedByFive(IEnumerable<int> numbers)
    foreach (int number in numbers)
        if ((number/5) > 1)
            yield return number;

The Solution

In the above way, we will add more methods as the new conditions come. But there is a better way to face this problem. We can and should use delegate to avoid rewriting a fresh method every time we get by a new rule we want to apply for this array. Use of Func as method parameter we will have the leverage to decouple the caller and the function we want to use. Func will pass the rule to the method body and will apply it.

public IEnumerable<int> GetNumbers(IEnumerable<int> numbers, Func<int, bool> numberResolver)
    foreach (int number in numbers)
        if (numberResolver(number))
            yield return number;
IEnumerable<int> numbers = new[] {3, 4, 7, 1, 8, 10, 21, 5, 9, 11, 14, 19};

IEnumerable<int> greaterThanTen = GetNumbers(numbers, x=>x>10);


IEnumerable<int> greaterThanOneAfterDividedByFive = GetNumbers(numbers, n => (n/5) > 1);

The above code is pretty self-explanatory. Func uses Lambda expression which is essentially an anonymous function.

For extensibility standpoint, Func is very effective. While writing various extension methods, you will find it extremely useful.

Getting TResult

The x-factor of Func is probably Func<TResult>. For functional programming, the return type has great use. For example:

Func<int, int> square = num => num*num;

…also, we can bring the previous example here see a bit more complex scenario.

IEnumerable<int> numbers = new[] { 3, 4, 7, 1, 8, 10, 21, 5, 9, 11, 14, 19 };
Func<IEnumerable<int>, IEnumerable<int>> getGreaterThanTen = nums => 
    var array = new List<int>();
    nums.ToList().ForEach(x =>
        if (x > 10)
    return array;

var result = getGreaterThanTen(numbers);



This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Md Nazmoon Noor
Software Developer (Senior)
Bangladesh Bangladesh
No Biography provided

Comments and Discussions

QuestionMy Vote of 5 PinmemberFaisal(mfrony)14-May-14 1:33 
GeneralMy vote of 5 PinprofessionalMonjurul Habib14-May-14 1:09 
GeneralRe: My vote of 5 PinmemberMd Nazmoon Noor14-May-14 1:24 
QuestionWon't Work Pinmemberhansonprogrammer12-May-14 17:23 
AnswerRe: Won't Work PinmemberMd Nazmoon Noor13-May-14 1:42 
GeneralMy vote of 5 PinmemberHumayun Kabir Mamun11-May-14 21:28 
GeneralRe: My vote of 5 PinmemberMd Nazmoon Noor11-May-14 21:35 
GeneralMy vote of 2 PinmemberAlexander Sharykin11-May-14 20:12 
QuestionFormat PinmemberNelek11-May-14 6:15 
AnswerRe: Format PinmemberMd Nazmoon Noor11-May-14 7:11 
GeneralRe: Format PinmemberNelek11-May-14 7:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140922.1 | Last Updated 11 May 2014
Article Copyright 2014 by Md Nazmoon Noor
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid