Using types defined in C# assembly in discriminated union

Hi again!

Have another question about something I’m attempting to do with creating discriminated unions using classes from another assembly:

open Assembly.Path.To.Types
type Item1 = Assembly.Path.To.Types.Item1
type Item2 = Assembly.Path.To.Types.Item2
type Items = 
    | Item1 of Item1
    | Item2 of Item2

let matchOnKey key = 
    match key with
    | "key1" -> new Item1(Field = "initialized!")
    | "key2" -> new Item2(Field = 1)

The compiler is having none of this. any idea what I might be doing wrong here? I was under the impression that I should be able to create types from any .net assembly and use them in unions, but i just get: All branches of a pattern match expression must return values of the same type as the first branch, which here is ‘Item1’. I’ve tried casting them both to the Items type in the match statement but no dice.

Thanks in advance! :smiley:

It’s because a function needs to return the same thing in all branches. If key matches “key1”, the return type will be Item1. If it matches “key2”, the return type will be Item2. That’s no good, for example, you wouldn’t expect this to work either:

let matchOnKey key = 
    match key with
    | "key1" -> 1
    | "key2" -> "string"

What you need to do is ensure they’re of the same type, in this case, type Items. Each case of a DU can be thought of as a constructor for that type. So you would change your example to:

let matchOnKey key = 
    match key with
    | "key1" -> Items.Item1 (new Item1(Field = "initialized!"))
    | "key2" -> Items.Item2 (new Item2(Field = 1))

This can be written a few of different ways actually. You could also write it as:

let matchOnKey key = 
    match key with
    | "key1" -> Item1(Field = "initialized!") |> Items.Item1
    | "key2" -> Item2(Field = 1) |> Items.Item2

assuming that types Item1 and Item2 don’t implement IDisposable (in that case, the compiler would give a warning and tell you that it’s recommended to use new rather than omitting it).

Hope this helps!

1 Like

Thank you very much for your help :slight_smile: