How to tell if an enum property has been set? C#
You can use one of two methods: default enum value or a nullable enum.
Default enum value
Since an enum is backed by an integer, and int
defaults to zero, the enum will always initialize by default to the value equivalent to zero. Unless you explicitly assign enum values, the first value will always be zero, second will be one, and so on.
public enum Color
{
Undefined,
Red,
Green
}
// ...
Assert.IsTrue(Color.Undefined == 0); // success!
Nullable enum
The other way to handle unassigned enum is to use a nullable field.
public class Foo
{
public Color? Color { get; set; }
}
// ...
var foo = new Foo();
Assert.IsNull(foo.Color); // success!
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;
}
}
}
Enums are Value Types, which means they are not references to an object stored somewhere else, and hence they cannot be null
. They always have a default value just like int
which will default to zero upon creation. I suggest two approaches:
Add another enum entry called e.g.,
None
with value equal to zero. This way your enum value will default toNone
upon creation. Then you can checkif(foo.ColorType != Color.None)
.Make your
Color
property a nullable one like:public Color? ColorType { get; set; }
. Now it will default tonull
and can be assigned the valuenull
. Read more aboutnullable
types here: MSDN - Nullable Types (C#).