Thanks to visit codestin.com
Credit goes to github.com

Skip to content

System.Func<TResult> F# snippets #7607

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
module Delegate

// <Snippet1>
open System.IO

type WriteMethod = delegate of unit -> bool

type OutputTarget() =
member _.SendToFile() =
try
let fn = Path.GetTempFileName()
use sw = new StreamWriter(fn)
sw.WriteLine "Hello, World!"
true
with _ ->
false

let output = new OutputTarget()
let methodCall = WriteMethod output.SendToFile
if methodCall.Invoke() then
printfn "Success!"
else
printfn "File write operation failed."

// </Snippet1>
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
module Example

// <Snippet5>
open System

type LazyValue<'T>(func: Func<'T>) =
let mutable value = ValueNone

member _.Value =
match value with
| ValueSome v -> v
| ValueNone ->
// Execute the delegate.
let v = func.Invoke()
value <- ValueSome v
v

let expensiveOne () =
printfn "\nExpensiveOne() is executing."
1

let expensiveTwo (input: string) =
printfn "\nExpensiveTwo() is executing."
int64 input.Length

// Note that each lambda expression has no parameters.
let lazyOne = LazyValue(fun () -> expensiveOne ())
let lazyTwo = LazyValue(fun () -> expensiveTwo "apple")

printfn "LazyValue objects have been created."

// Get the values of the LazyValue objects.
printfn $"{lazyOne.Value}"
printfn $"{lazyTwo.Value}"


// The example produces the following output:
// LazyValue objects have been created.
//
// ExpensiveOne() is executing.
// 1
//
// ExpensiveTwo() is executing.
// 5
// </Snippet5>
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
module Func1

// <Snippet2>
open System
open System.IO

type OutputTarget() =
member _.SendToFile() =
try
let fn = Path.GetTempFileName()
use sw = new StreamWriter(fn)
sw.WriteLine "Hello, World!"
true
with _ ->
false

let output = OutputTarget()
let methodCall = Func<bool> output.SendToFile
if methodCall.Invoke() then
printfn "Success!"
else
printfn "File write operation failed."

// </Snippet2>
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
module Lambda

// <Snippet4>
open System
open System.IO

type OutputTarget() =
member _.SendToFile() =
try
let fn = Path.GetTempFileName()
use sw = new StreamWriter(fn)
sw.WriteLine "Hello, World!"
true
with _ ->
false

let output = OutputTarget()
let methodCall = Func<bool>(fun () -> output.SendToFile())
if methodCall.Invoke() then
printfn "Success!"
else
printfn "File write operation failed."
// </Snippet4>
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Compile Include="Delegate.fs" />
<Compile Include="Func1.fs" />
<Compile Include="Lambda.fs" />
<Compile Include="Example.fs" />
</ItemGroup>
</Project>
10 changes: 8 additions & 2 deletions xml/System/Func`1.xml
Original file line number Diff line number Diff line change
Expand Up @@ -77,25 +77,28 @@
You can use this delegate to represent a method that can be passed as a parameter without explicitly declaring a custom delegate. The encapsulated method must correspond to the method signature that is defined by this delegate. This means that the encapsulated method must have no parameters and must return a value.

> [!NOTE]
> To reference a method that has no parameters and returns `void` (or in Visual Basic, that is declared as a `Sub` rather than as a `Function`), use the <xref:System.Action> delegate instead.
> To reference a method that has no parameters and returns `void` (`unit`, in F#) (or in Visual Basic, that is declared as a `Sub` rather than as a `Function`), use the <xref:System.Action> delegate instead.

When you use the <xref:System.Func%601> delegate, you do not have to explicitly define a delegate that encapsulates a parameterless method. For example, the following code explicitly declares a delegate named `WriteMethod` and assigns a reference to the `OutputTarget.SendToFile` instance method to its delegate instance.

:::code language="csharp" source="~/samples/snippets/csharp/VS_Snippets_CLR_System/system.Func~1/cs/Delegate.cs" interactive="try-dotnet" id="Snippet1":::
:::code language="fsharp" source="~/samples/snippets/fsharp/VS_Snippets_CLR_System/system.Func~1/fs/Delegate.fs" id="Snippet1":::
:::code language="vb" source="~/samples/snippets/visualbasic/VS_Snippets_CLR_System/system.Func~1/vb/Delegate.vb" id="Snippet1":::

The following example simplifies this code by instantiating the <xref:System.Func%601> delegate instead of explicitly defining a new delegate and assigning a named method to it.

:::code language="csharp" source="~/samples/snippets/csharp/VS_Snippets_CLR_System/system.Func~1/cs/Func1.cs" interactive="try-dotnet" id="Snippet2":::
:::code language="fsharp" source="~/samples/snippets/fsharp/VS_Snippets_CLR_System/system.Func~1/fs/Func1.fs" id="Snippet2":::
:::code language="vb" source="~/samples/snippets/visualbasic/VS_Snippets_CLR_System/system.Func~1/vb/Func1.vb" id="Snippet2":::

You can use the <xref:System.Func%601> delegate with anonymous methods in C#, as the following example illustrates. (For an introduction to anonymous methods, see [Anonymous Methods](/dotnet/csharp/programming-guide/statements-expressions-operators/anonymous-methods).)

:::code language="csharp" source="~/samples/snippets/csharp/VS_Snippets_CLR_System/system.Func~1/cs/Anon.cs" interactive="try-dotnet" id="Snippet3":::

You can also assign a lambda expression to a <xref:System.Func%602> delegate, as the following example illustrates. (For an introduction to lambda expressions, see [Lambda Expressions](/dotnet/visual-basic/programming-guide/language-features/procedures/lambda-expressions) and [Lambda Expressions](/dotnet/csharp/programming-guide/statements-expressions-operators/lambda-expressions).)
You can also assign a lambda expression to a <xref:System.Func%602> delegate, as the following example illustrates. (For an introduction to lambda expressions, see [Lambda Expressions (VB)](/dotnet/visual-basic/programming-guide/language-features/procedures/lambda-expressions), [Lambda Expressions (C#)](/dotnet/csharp/programming-guide/statements-expressions-operators/lambda-expressions), and [Lambda Expressions (F#)](/dotnet/fsharp/language-reference/functions/lambda-expressions-the-fun-keyword/).)

:::code language="csharp" source="~/samples/snippets/csharp/VS_Snippets_CLR_System/system.Func~1/cs/Lambda.cs" interactive="try-dotnet" id="Snippet4":::
:::code language="fsharp" source="~/samples/snippets/fsharp/VS_Snippets_CLR_System/system.Func~1/fs/Lambda.fs" id="Snippet4":::
:::code language="vb" source="~/samples/snippets/visualbasic/VS_Snippets_CLR_System/system.Func~1/vb/Lambda.vb" id="Snippet4":::

The underlying type of a lambda expression is one of the generic `Func` delegates. This makes it possible to pass a lambda expression as a parameter without explicitly assigning it to a delegate. In particular, because many methods of types in the <xref:System.Linq> namespace have `Func` parameters, you can pass these methods a lambda expression without explicitly instantiating a `Func` delegate.
Expand All @@ -110,13 +113,16 @@
The example creates two methods and instantiates two `LazyValue` objects with lambda expressions that call these methods. The lambda expressions do not take parameters because they just need to call a method. As the output shows, the two methods are executed only when the value of each `LazyValue` object is retrieved.

:::code language="csharp" source="~/samples/snippets/csharp/VS_Snippets_CLR_System/system.Func~1/cs/Example.cs" interactive="try-dotnet" id="Snippet5":::
:::code language="fsharp" source="~/samples/snippets/fsharp/VS_Snippets_CLR_System/system.Func~1/fs/Example.fs" id="Snippet5":::
:::code language="vb" source="~/samples/snippets/visualbasic/VS_Snippets_CLR_System/system.Func~1/vb/Example.vb" id="Snippet5":::

]]></format>
</remarks>
<related type="Article" href="/dotnet/csharp/programming-guide/statements-expressions-operators/lambda-expressions">Lambda Expressions (C# Programming Guide)</related>
<related type="Article" href="/dotnet/fsharp/language-reference/functions/lambda-expressions-the-fun-keyword">Lambda Expressions: The fun Keyword (F#)</related>
<related type="Article" href="/dotnet/visual-basic/programming-guide/language-features/procedures/lambda-expressions">Lambda Expressions</related>
<related type="Article" href="/dotnet/csharp/programming-guide/delegates/">Delegates (C# Programming Guide)</related>
<related type="Article" href="/dotnet/fsharp/language-reference/delegates/">Delegates (F#)</related>
<related type="Article" href="/dotnet/visual-basic/programming-guide/language-features/delegates/">Delegates in Visual Basic</related>
</Docs>
</Type>