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.IsDefined
would 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: Enum
is not valid. This means thatenumType
can be anything, liketypeof(object)
, there is no mechanism in the language to constraintenumType
to only enumeration types. This can makeEnum.IsDefined
throw, 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
Enum
is 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.SomeValue
would returntrue
and(SomeEnumeration)5
would returnfalse
unless there is a member of the enumeration with that value.