Blog

Filter posts by the Tags of Blog section!

Declaration of Func delegates in C# Monday, 07 March 2016

Based on Microsoft definition "Func is a generic delegate that encapsulates a method that can accept parameters and return some value." There is about 17 override for Func in Dot Net. Here is the different declaration of Func delegate in C#:

 


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 T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, in T14, in T15, in T16, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15, T16 arg16);

 

As you can see The first delegate cannot accept parameters and return Type that is specified by the TResult parameter. For example:

 

 Func<double> func = () => Math.PI / 3;

 

Or

 

Func<int, string> func = (x) => string.Format("value={0}", x);

 

These samples are the usage Fun with Lambda Expression. Rather than Lambda Expression, Fun provides a way to store anonymous methods in a generalized way. For example:

 

public static string Sum(int a, int b)

        {

            string result = string.Format("Sum:{0}", a + b);

            return result;

        }

 

  static void Main(string[] args)

        {

 

            Func<int, int, string> func = Sum;

            string result = func(4, 5);

            Console.WriteLine(result);

      }
 

 

Finally, Fun can be used as anonymous functions:

 

static void Main(string[] args)

        {

               Func<int, int, string> func3 = delegate (int a, int b)

             {

                 string result3 = string.Format("Sum:{0}", a + b);

                 return result3;

             };
 

 

            string result = func3(4, 5);

            Console.WriteLine(result);

 

        }

 

Tags: C#

comments powered by Disqus