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.
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.
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.
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.
You can have methods on enums which take parameters. Java enums are not union types like in some other languages.
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
This should work:
type Gender =
| [<Display>] Undisclosed = 0
| [<Display>] Male = 1
| [<Display>] Female = 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With