Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Annotations for enums in F#

Tags:

enums

f#

I have an enum in F#:

type Gender = Undisclosed = 0 | Male = 1 | Female = 2

The equivalent C# code would be

public enum Gender
{
    Undisclosed,
    Male,
    Female
}

In fact, in C#, I can go one step better. To use gender in a dropdown in a cshtml page, I can do this:

public enum Gender
{
    [Display(ResourceType = typeof(LocalisedStrings), Name = "GenderUndisclosed")] Undisclosed,
    [Display(ResourceType = typeof(LocalisedStrings), Name = "GenderMale")] Male,
    [Display(ResourceType = typeof(LocalisedStrings), Name = "GenderFemale")] Female
}

Unfortunately, the F# compiler says that "attributes are not allowed here" if I try to add similar annotations to the F# enum members. Is there a way around this? I'd like to avoid creating a duplicate class and performing Automapper voodoo if I possibly can.

like image 812
Rob Lyndon Avatar asked Jul 02 '16 16:07

Rob Lyndon


People also ask

Can you use == for enums?

Because there is only one instance of each enum constant, it is permissible to use the == operator in place of the equals method when comparing two object references if it is known that at least one of them refers to an enum constant.

What are enums and annotations Java?

Enums could be treated as a special type of classes and annotations as a special type of interfaces. The idea of enums is simple, but quite handy: it represents a fixed, constant set of values. What it means in practice is that enums are often used to design the concepts which have a constant set of possible states.

How do you declare an enum variable?

An enum is defined using the enum keyword, directly inside a namespace, class, or structure. All the constant names can be declared inside the curly brackets and separated by a comma. The following defines an enum for the weekdays. Above, the WeekDays enum declares members in each line separated by a comma.

Can enums have parameters?

You can have methods on enums which take parameters. Java enums are not union types like in some other languages.


2 Answers

You need a | before the attribute.

// Doesn't compile. "Attributes are not allowed here"
type Foo = [<Bar>] Baz = 0

// Compiles.
type Foo = | [<Bar>] Baz = 0

In your case, this would come out to:

type Gender = 
    | [<Display(ResourceType = typeof<LocalisedStrings>, Name = "GenderUndisclosed")>] Undisclosed = 0
    | [<Display(ResourceType = typeof<LocalisedStrings>, Name = "GenderMale")>] Male = 1
    | [<Display(ResourceType = typeof<LocalisedStrings>, Name = "GenderFemale")>] Female = 2
like image 90
31eee384 Avatar answered Dec 19 '22 20:12

31eee384


This should work:

type Gender = 
    | [<Display>] Undisclosed = 0 
    | [<Display>] Male        = 1 
    | [<Display>] Female      = 2
like image 36
krontogiannis Avatar answered Dec 19 '22 21:12

krontogiannis