C-Sharp Func Delegate

Func is a generic delegate included with in System namespace. It has zero to 16 input parameters and one out parameter with same return type of out parameter. The last parameter is considered as an out parameter.

Func delegate with zero argument

public delegate TResult Func();

Func delegate with 16 arguments

public delegate TResult Func(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,TResult argResult);

Step 1: Lets take a look of old delegate version.

using System; namespace ConsoleApp1 { delegate bool Greatest(int a, int b); class Program { public static bool IsGreater(int a, int b) { return (a > b); } static void Main(string[] args) { Greatest s = new Greatest(IsGreater); Console.WriteLine(s(12, 34)); Console.ReadKey(); } } }

Step 2: Now we will assign IsGreater method to Func<int, int, bool> s it will takes two int type variables as input and reutns boolean type result.

using System; namespace ConsoleApp1 { class Program { public static bool IsGreater(int a, int b) { return (a > b); } static void Main(string[] args) { Func<int, int, bool> s = IsGreater; Console.WriteLine(s(12, 34)); Console.ReadKey(); } } }

Step 3: Next, we will replace entire function body and assign it to Func as follows.

using System; namespace ConsoleApp1 { class Program { static void Main(string[] args) { Func<int, int, bool> s = delegate (int a, int b) { return a > b; }; Console.WriteLine(s(12, 34)); Console.ReadKey(); } } }

Step 4: Next moreover we can also remove delegate keyword too.

using System; namespace ConsoleApp1 { class Program { static void Main(string[] args) { Func<int, int, bool> s = (a, b) => { return (a > b); }; Console.WriteLine(s(12, 34)); Console.ReadKey(); } } }

Step 5: Next moreover we can also remove return keyword too.

using System; namespace ConsoleApp1 { class Program { static void Main(string[] args) { Func<int, int, bool> s = (a, b) => (a > b); Console.WriteLine(s(12, 34)); Console.ReadKey(); } } }

If you have any query or question or topic on which, we might have to write an article for your interest or any kind of suggestion regarding this post, Just feel free to write us, by hit add comment button below or contact via Contact Us form.


Your feedback and suggestions will be highly appreciated. Also try to leave comments from your valid verified email account, so that we can respond you quickly.

 
 

{{c.Content}}

Comment By: {{c.Author}}  On:   {{c.CreatedDate|date:'dd/MM/yyyy'}} / Reply


Categories