I am creating a validation class using FluentValidation in C#, to validate that my Type property of Account class is of type AccountType enum.
What would be the correct implementation of this:
RuleFor (account => account.Type)
.IsInEnum (....)
You could do the following:
The code can use some explanation:
The first check simply makes sure that the value of the enumeration and the type of the enumeration are the same. If they are not, the method must return, obviously,
false. But why is this necessary?Enum.IsDefinedwould cover this too, right?Ideally, we'd want a method with the following signature:
IsDefinedIn<T>(this T value) where T: Enum. This would be totally type safe at compile time but, sadly, the constraintT: Enumis not valid. This means thatenumTypecan be anything, liketypeof(object), there is no mechanism in the language to constraintenumTypeto only enumeration types. This can makeEnum.IsDefinedthrow, if you don't want this happening, you should keep the first check.Do consider that you should throw (or assert) if passing some type that is not an
Enumis a bug in your code. I've just shown you how you could get around this issue if necessary.The second check simply makes sure the value is defined in the enumeration.
SomeEnumeration.SomeValuewould returntrueand(SomeEnumeration)5would returnfalseunless there is a member of the enumeration with that value.