Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# out parameters and value types

Tags:

f#

c#-to-f#

The following f# function works great if I pass references to objects, but will not accept structs, or primitives:

let TryGetFromSession (entryType:EntryType, key, [<Out>]  outValue: 'T byref) =
    match HttpContext.Current.Session.[entryType.ToString + key] with 
             | null -> outValue <- null; false
             | result -> outValue <- result :?> 'T; true

If I try to call this from C# with:

bool result = false;
TryGetFromSession(TheOneCache.EntryType.SQL,key,out result)

I get The Type bool must be a reference type in order to use it as a parameter Is there a way to have the F# function handle both?

like image 890
jackmott Avatar asked Feb 08 '23 20:02

jackmott


1 Answers

The problem is that the null value in outValue <- null restricts the type 'T to be a reference type. If it has null as a valid value, it cannot be a value type!

You can fix that by using Unchecked.defaultOf<'T> instead. This is the same as default(T) in C# and it returns either null (for reference types) or the empty/zero value for value types.

let TryGetFromSession (entryType:EntryType, key, [<Out>]  outValue: 'T byref) =
    match HttpContext.Current.Session.[entryType.ToString() + key] with 
    | null -> outValue <- Unchecked.defaultof<'T>; false
    | result -> outValue <- result :?> 'T; true
like image 142
Tomas Petricek Avatar answered Feb 15 '23 08:02

Tomas Petricek