Alex Rivera | Logout

How to tell if an enum property has been set? C#

Asked 2013-05-14T23:48:14.980
31

I have a class with an enum property like so:

public class Foo
{
    public Color ColorType {get;set;}
}

public enum Color
{
    Red,
    Green,
}

Now this class can be initialized like so:

var foo = new Foo();

without the ColorType property ever being set. Now, I'm trying to create a method and perform actions on whether that enum was ever set or not, for example I have a method

private void checkEnum(Foo foo)
{
    if(foo.ColorType !=null)
    {
        //perform these actions
    }else
    {
        //perform those actions
    }
}

however I get a warning saying that value will never be null and upon further research, if the enum is never set if will default to the first value which would be Red in my case, I was thinking about adding a value to my enum which would be 'not set' and make that value the first one, so if it hasnt been set then the enum will have the value 'not set', is there a better way of doing this, my proposed method seems like it could get messy

Edit
Report

1 Answer

7

You can make it so that the underlying private field is nullable, but the property is not.

E.g.

class SomeClass
{
    private Color? _color; // defaults to null

    public Color Color
    {
        get { return _color ?? Color.Black; }
        set { _color = value; }
    }

    public bool ColorChanged
    {
        get { return _color != null; }
    }
}

That way if color == null you know it hasn't been set yet, and you are also stopping the user from setting it to null (or undefined as other answers specify). If color is null you have 100% certainty that the user has not set it ever.

Only catch is the default value returned by the get but you could always throw an excepting if it better matches your program.

You can also take it one step further by making it so that the set only sets the field if the given value is not equal to the default value (depending on your use case):

public Color Color
{
    get { return _color ?? Color.Black; }
    set
    {
        if (value != Color)
        {
            _color = value;
        }
    }
}
answered 2013-05-24T03:52:01.937

Your Answer