Accessing FSharp’s Option type from C#

Here’s a view-model class written in F#:

type ClaimsSummaryViewModel(memberId , dispatcher:Dispatcher , repository:IClaimsRepository) = 

    member val FamilySummary =      None   with get,set
    member val DependentSummaries = seq [] with get,set
    member val DependentSummary =   None   with get,set

    member this.Load() =
        this.FamilySummary      <- repository.GetFamilySummary      memberId
        this.DependentSummaries <- repository.GetDependentSummaries memberId

    member this.SetDependentSummary summary =
        this.DependentSummary <- Some summary

    member this.ViewClaims =

        DelegateCommand( (fun _ -> match this.DependentSummary with
                                   | Some v -> dispatcher.ViewMemberClaims v.Member.MemberId
                                   | None   -> ()), 
                         fun _ -> true ) :> ICommand

The following enables C# to access an Option type hosted by the FSharp.Core library:

using Microsoft.FSharp.Core;
using static Claims;

namespace Healthcare.Android
    static class Utility
        public static bool IsSome<T>(this FSharpOption<T> option) => FSharpOption<T>.get_IsSome(option);
        public static bool IsNone<T>(this FSharpOption<T> option) => FSharpOption<T>.get_IsNone(option);

Here’s an example of how to access an option type from a Xamarin.Android application:

            var familySummary = FindViewById<TextView>(Resource.Id.FamilySummaryValue);
            familySummary.Text = _viewModel.FamilySummary.IsSome()
                ? _viewModel.FamilySummary.Value.Claims.Count().ToString()
                : string.Empty;

One Reply to “Accessing FSharp’s Option type from C#”

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s