c# - How to set enum to null -
i have enum
string name;  public enum color {   red,   green,   yellow } how set null on load.
name = ""; color color = null; //error edited: bad, didn't explain properly. answers related nullable perfect. situation if, have get/set enum in class other elements name, etc. on page load initiallize class , try default values null. here scenario (code in c#):
namespace testing {     public enum validcolors     {         red,         green,         yellow     }      public class enumtest     {         private string name;         private validcolors mycolor;          public string name         {             { return name; }             set { name = value; }         }          public validcolors mycolor         {             { return mycolor; }             set { mycolor = value; }         }      }      public partial class _default : system.web.ui.page     {                protected void page_load(object sender, eventargs e)         {             enumtest oenumtest = new enumtest();             oenumtest.name = "";             oenumtest.mycolor = null; //???         }     }  } then using suggestions below changed above code make work , set methods. need add "?" in enumtest class during declaration of private enum variable , in get/set method:
public class enumtest {     private string name;     private validcolors? mycolor; //added "?" here in declaration , in get/set method      public string name     {         { return name; }         set { name = value; }     }      public validcolors? mycolor     {         { return mycolor; }         set { mycolor = value; }     }  } thanks lovely suggestions.
you can either use "?" operator nullable type.
public color? mycolor = null; or use standard practice enums cannot null having first value in enum (aka 0) default value. example in case of color none.
public color mycolor = color.none; 
Comments
Post a Comment