properties - How to tell if an enum property has been set? C# -
i have class enum property so:
public class foo { public color colortype {get;set;} } public enum color { red, green, }
now class can initialized so:
var foo = new foo();
without colortype property ever being set. now, i'm trying create method , perform actions on whether enum ever set or not, example have method
private void checkenum(foo foo) { if(foo.colortype !=null) { //perform these actions }else { //perform actions } }
however warning saying value never null , upon further research, if enum never set if default first value red in case, thinking adding value enum 'not set' , make value first one, if hasnt been set enum have value 'not set', there better way of doing this, proposed method seems messy
you can use 1 of 2 methods: default enum value or nullable enum.
default enum value
since enum backed integer, , int
defaults zero, enum initialize default value equivalent zero. unless explicitly assign enum values, first value zero, second one, , on.
public enum color { undefined, red, green } // ... assert.istrue(color.undefined == 0); // success!
nullable enum
the other way handle unassigned enum use nullable field.
public class foo { public color? color { get; set; } } // ... var foo = new foo(); assert.isnull(foo.color); // success!
Comments
Post a Comment