F # Equivalent to Enum.TryParse

In C #, the following code applies:

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 he complains

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

What does this mean in the world?

+6
source share
1 answer

This is a pretty useless (if technically correct) message that the compiler gives if you try to parse the disqualified join value using Enum.TryParse .

More precisely, if you look at this function, you will see that it is parameterized with a type that is limited to a value type with a standard constructor. DUs do not meet any of these criteria - this is what the compiler complains about.

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

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

Skipping values ​​will cause the compiler to interpret this type as a discriminatory union, which is a completely different beast.

+7
source

Source: https://habr.com/ru/post/1013800/


All Articles