Initialize an enumeration with a null value

How to create an enumeration with a null value

Example:

public enum MyEnum { [StringValue("X")] MyX, [StringValue("Y")] MyY, None } 

where None is null or String.Empty

+8
c #
source share
5 answers

You can try something like this: -

 public MyEnum? value= null; 

or you can try the following: -

  public MyEnum value= MyEnum.None; 
+15
source share

Like all other answers, you cannot have a null enum value. What you can do is add a Description attribute (like your StringValue ) that has a null value.

For example:

 public enum MyEnum { [Description(null)] None = 0, [Description("X")] MyX, [Description("Y")] MyY } 

You can get a description of Enum with the following function:

  public static string GetEnumDescription(Enum value) { FieldInfo fi = value.GetType().GetField(value.ToString()); DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes( typeof(DescriptionAttribute), false); if (attributes != null && attributes.Length > 0) return attributes[0].Description; else return value.ToString(); } 

Application:

 MyEnum e = MyEnum.None; string s2 = GetEnumDescription((MyEnum)e); // This returns null 
+5
source share

All enumeration types are value types, and different members are also inferred from member types (valid types are byte , sbyte , short , ushort , int , uint , long , or ulong - as documented ).

This means enumeration members cannot be null .

One way to deal with the default enum value is to put the value None as the first value and set it to a negative value (for signed enumerations) or 0 .

 public enum MyEnum { [StringValue(null)] None = -1, [StringValue("X")] MyX, [StringValue("Y")] MyY } 

Could you have a null reference to an enumeration if you declare a nullable instance - myenum? .

+4
source share

use "?" oeprator for type NULL!

 public MyEnum? myEnum= null; 
+4
source share

There is no such thing as an "enumeration with a null value". An enumeration in C # is only a named integer. In your case, None is just an alias for 2 (for completeness, MyX is 0 and MyY is 1 ). By default, the base rename data type is int , but it can also be other primitive types with different size / sign values.

If you want a null enumeration, will you need to use MyEnum? , aka Nullable<MyEnum> .

+2
source share

All Articles