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.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
VulpesPosted Jul 28, 2014, 7:42 AM
VulpesPosted Jul 28, 2014, 9:13 AM
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:
Hemant MehraPosted Jul 28, 2014, 7:59 AM
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.