F# Equivalent of Enum.TryParse

979 views Asked by At

In C#, the following code is valid:

MyEnum myEnum = MyEnum.DEFAULT;
if (Enum.TryParse<MyEnum>(string, out myEnum))
{
    Console.WriteLine("Success!");
}

So I thought I would use this in F#. Here is my attempt:

let mutable myEnum = MyEnum.DEFAULT
if Enum.TryParse<MyEnum>(string, &myEnum) then
    printfn "Success!"

But it complains

a generic construct requires that the type 'MyEnum' have a default constructor

What in the world does that mean?

1

There are 1 answers

0
scrwtp On BEST ANSWER

This is a rather unhelpful (if technically correct) message that the compiler gives you if you try to parse a discriminated union value using Enum.TryParse.

More precisely, if you look at that function, you'll see that it's parameterized with a type that's constrained to be a value type with a default constructor. DU's meet neither of this criteria - this is what the compiler complains about.

When defining an enum in F#, unlike C#, you need to explicitly give each label a value:

type MyEnum = 
    | Default = 0
    | Custom = 1
    | Fancy = 2

Skipping the values would make the compiler interpret the type as a discriminated union, which is a very different beast.