One extremely common scenario that you come across when programming is that you want to evaluate if a property of a type has one of a few of a given set of values. It could be an object that should be treated in a certain manner if a property is A, B or C, but not D. It is really a simple scenario, but it is still worth choosing your approach carefully.

Let’s take an example:

public enum Location
{
    MyHouse,
    MyYard,
    MyNeighbourhood,
    MyTown
    MyCounty,
    MyCountry
}

public class Kid
{
    public Location Location { get; private set; }
}

public class Me
{
    public Kid MyKid { get; set; }

    public Me(Kid myKid)
    {
        MyKid = myKid;
    }

    public bool KidIsOutsideCallingRange
    {
        get
        {
            // not yet implemented
        }
    }
}

Now, there are two obvious approaches in implementing KidIsOutsideCallingRange:

Include the states that means that my kid is outside of my calling range:

return MyKid.Location == Location.MyNeighbourhood
       || MyKid.Location == Location.MyTown
       || MyKid.Location == Location.MyCounty
       || MyKid.Location == Location.MyCountry;

Exclude the states that means that my kid is within of my calling range:

return MyKid.Location != Location.MyHouse
       && MyKid.Location != Location.MyYard;

Both those approaches will yield the same result. Today, that is. The choice will become interesting when the Location enum changes, and new values are added to it. With the first approach, KidIsOutsideCallingRange will be false for any new values, while the behavior will be the opposite with the second approach.

Which one that is correct depends entirely on the context, even though I personally tend to lean towards the first approach; I like how it makes the decision by deliberately including known values. If the Location property has any of the given states, we know that it is outside of the calling range. With other states it may or may not be, but we cannot be certain.


I am working for a great consultancy company called Diversify, located in Sweden. We are hiring skilled .NET developers. If you are interested, don't hesitate to get in touch with me.

Comments