Requiring Parameter Value to be a Valid Enum Value Using a Code Contract

Let's suppose that you have an Enum in C#, that has four values:

public enum Direction

and you have a method

public void GoDirection(Direction direction)

An enum is really just an Int32, with some additional compiler support for the syntax. The four values, since they weren't specified, are North=0, East=1, South=2, and West=3. With a cast, however, any valid Int32 value can be passed into the GoDirection method. So most often, you would pass in one of the four directions, like this:


But you could just as well do this:


Most often, if a value that isn't one of the four values is passed in, it is a bug. It would help if a Code Contract verified that it was one of the four values. You can apply a contract to verify that the value passed in is one of the four like this:

public void GoDirection(Direction direction)
        Enum.IsDefined(typeof(Direction), direction);
    // other code

This causes the Contract not to validate if the direction is not one of the four given by the Direction enum (so passing in 200 is an error). Your Code Contract settings (in the Project Properties) will determine when this verification happens. By default this verification would only happen in Debug builds, and not even compiled into the code on Release builds, but you can change that if you like.

No comments :

Post a Comment

Note: Only a member of this blog may post a comment.