Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# Equivalent of Enum.TryParse

Tags:

enums

f#

tryparse

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?

like image 681
user3685285 Avatar asked Jan 05 '17 16:01

user3685285


1 Answers

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.

like image 157
scrwtp Avatar answered Sep 17 '22 12:09

scrwtp