umbersar
umbersar

Reputation: 1931

pattern matching in C# for type defined in F#

I have declared a type in F# that i now want to consume in C#. The type definition is:

type ConstObj = {value:int;}

type Instruction =
      | CONST of ConstObj
      | HALT

I can successfully pattern match CONST Instruction but can't match HALT as the compiler throws an error during compilation saying "CS0426 The type name 'HALT' does not exist in the type 'Types.Instruction'"

   private void Eval(Instruction instruction) {
        switch (instruction) {
            case Instruction.CONST c:
                break;
            case Instruction.HALT h:
                break;
            default:
                break;
        }
    }

But the same type can be successfully pattern matched in F#:

  let matcher x = 
      match x with
      | Instruction.CONST{value=v;} ->
            printfn "Const instruction. Value is %i" v 
      | Instruction.HALT ->
          printfn "HALT instruction" 

Any ideas?

Upvotes: 4

Views: 70

Answers (1)

TheQuickBrownFox
TheQuickBrownFox

Reputation: 10624

This answer is completely stolen from this blog post.

C# can't pattern match on empty DU cases from F#. Some possible workarounds:

type Record = { Name: string; Age: int }

type Abc =
    | A
    | B of double
    | C of Record
void HandleAbc(Abc abc)
{
    switch (abc)
    {
        // Option 1:
        case var x when x.IsA:
            Console.WriteLine("A");
            break;
        // Option 2:
        case var x when x == Abc.A:
            Console.WriteLine("A");
            break;
    }

    switch (abc.Tag)
    {
        // Option 3:
        case abc.Tags.A:
            Console.WriteLine("A");
            break;
    }
}

Upvotes: 3

Related Questions