Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# string to enum conversion

I have the following enum located in public class MyClass in namespace MyNamespace in a C#.NET DLL I reference and open from my F# module:

public enum MyEnum {
    ValueA,
    ValueB,
    ValueC}

I want to convert string s to its MyEnum equivalent (if possible) in my F# module. Trying to achieve it like...

let myEnumValue = (MyClass.MyEnum) (Enum.Parse(typedefof<MyClass.MyEnum>, s))

...gives me Invalid use of a type name and/or object constructor. If necessary use 'new' and apply the constructor to its arguments... error. Same if I use typeof<MyClass.MyEnum> instead of typedefof<MyClass.MyEnum>. Trying...

let myEnumValue = (typedefof<MyClass.MyEnum>) (Enum.Parse(typedefof<MyClass.MyEnum>, s))

...or...

let myEnumValue = (typeof<MyClass.MyEnum>) (Enum.Parse(typedefof<MyClass.MyEnum>, s))

... gives me The value is not a function and cannot be applied error.
I use MyEnum fine in other parts of my F# code, so I guess there is no problem with my C#.NET DLL.

And to avoid some likely questions :-)

  • I need converting string to enum because certain MyEnum values are serialised into an XML using .ToString() and the enums deserialised from XML will be passed on as parameters to an F# function
  • Using the int equivalent of MyEnum to write to and read from the XML is undesirable because the XML should be human-readable, plus it is more likely for the int equivalents of MyClass values to change than for those of .ToString().
like image 786
bugfoot Avatar asked Aug 01 '26 19:08

bugfoot


1 Answers

The problem with your code is the way that you are trying to cast the Object (returned by the Parse method) into an instance of MyClass.MyEnum. The syntax you attempted results in an "invalid use of a type name" error.

In F#, you down-cast as follows:

let myEnumValue = Enum.Parse(typedefof<MyClass.MyEnum>, s) :?> MyClass.MyEnum
like image 143
Wallace Kelly Avatar answered Aug 06 '26 03:08

Wallace Kelly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!