Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ToString exception while printing enum

Tags:

.net

f#

Given I have an enum:

type Cool = A = 'a'
          | B = 'b'

And i try to print it like so

printf "%A" Cool.A

I get the following exception:

ToString exception: The value passed in must be an enum base or an underlying type for an enum, such as an Int32. Parameter name: value

Why does this happen and (if possible) how I can fix this at the enum level?

like image 816
Paul Nikonowicz Avatar asked Aug 17 '12 21:08

Paul Nikonowicz


2 Answers

I can repro this on a machine with F# 2.0 compiler targeting .Net 4.0, but not with F# 2 targeting .Net 3.5 or less, or on a VS2012 (F# 3.0) machine (where .Net 4.5 supersedes 4.0).

I am not sure right now of the cause, but hopefully this info may help you or others narrow it down or find a workaround.

like image 96
Brian Avatar answered Nov 13 '22 23:11

Brian


I think it's better not to use char as base value for enum.
Although char seems to be allowed (MSDN article on F# enums), the corresponding article for C# says the opposite. Moreover, an older article says specifically:

base-type (Optional)
The underlying type that specifies the storage allocated for each enumerator. It can be one of the integral types except char. The default is int.

Looking at the source code of System.Enum.ToObject(Type,Object), it is also evident that char is not supported.

So, even if F# performs special handling of enum<char>, better to avoid it, keeping yourself from future integration problems.

like image 2
bytebuster Avatar answered Nov 13 '22 23:11

bytebuster