In which scenarios, Func<T> to use in c#?
As real time example, in which scenarios, Func can be used. What exactly Func does in C#?. Could you please explain with example?
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend4days leftRegister
VulpesRank #55 · 29.2K reputationPosted Jul 28, 2014, 3:42 AM EDT
Hemant MehraRank #4,439 · 343 reputationPosted Jul 28, 2014, 3:59 AM EDT
why we use delegate Func
like :-
using System;
class Test
{
static void Main()
{
string func = GetGreeting; // no parameters but returns a string
Console.WriteLine(func());
Console.ReadKey();
}
static string GetGreeting()
{
return "Hello Jitendra :)";
}
}
Can you clear me.
thanks in advance.
VulpesRank #55 · 29.2K reputationPosted Jul 28, 2014, 5:13 AM EDT
1. If you want to pass a method as an argument to another method.
2. If you want a method to return another method.
3. If you want to call more than one method at once.
Bearing in mind that lambda expressions can be automatically converted to compatible delegates, #1 is particularly useful in LINQ as it allows you to write code 'inline' rather than creating separate methods.
Delegates are also the basis for events in .NET. The latter are just a special kind of delegate where the only operations allowed outside the class in which the event is defined are += and -= which respectively add an event-handler to or remove an event-handler from the delegate's invocation list.
Here's another example which illustrates #1: