question

MrEdge-3552 avatar image
0 Votes"
MrEdge-3552 asked JackJJun-MSFT commented

What problem does Func solve?

I'm struggling to understand when and why I would use Func and what problem does it resolve?

I've read MSDN, tutorials teacher etc etc but all have examples but not necessarily explaining what problem it could resolve or when I could/should use it?

Could anyone give a very simple example(s) to demo this please?

dotnet-csharp
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

You can think of Func as a method assigned to a variable. A common pattern is passing a Func to another method. You get to assign any method you like as long as the inputs and outputs match the Func definition. This often reduces the amount of conditional statements needed because you define what logic to run (the body of the method) rather than doing a check first to figure out what method to call.

0 Votes 0 ·

Func is a specific delegate,you can refer to the link what-is-func-how-and-when-is-it-used to know why we need to use Func.


0 Votes 0 ·
Castorix31 avatar image
0 Votes"
Castorix31 answered

You can see this article for example : How and Why to Use Delegates in C#


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

karenpayneoregon avatar image
0 Votes"
karenpayneoregon answered

Another usage for projections.

Let's say you want to return a custom list as shown here from this model/class, we define a class as follows and shown below.

Func receives a Customer and returns a CustomerEntity. If this as a ASP.NET we would use mapping such as auto-mapper instead for CRUD, here it's in a desktop app working with Entity Framework Core.

117527-figure1.png

Also, when using LINQ/Lambda, Select, Where they use Func also as a predicate. Hover over a Select to see it. Also, read the docs and search for Func here



figure1.png (39.9 KiB)
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.