How do i create an enum with a null value
ex:
public enum MyEnum
{
[StringValue("X")]
MyX,
[StringValue("Y")]
MyY,
None
}
where None value is null or String.Empty
How do i create an enum with a null value
ex:
public enum MyEnum
{
[StringValue("X")]
MyX,
[StringValue("Y")]
MyY,
None
}
where None value is null or String.Empty
You can try something like this:-
public MyEnum? value= null;
or you can try this:-
public MyEnum value= MyEnum.None;
As all the other answers said, you can't have an enum value be null.
What you can do is add a Description
attribute (like your StringValue
) which has a null value.
For instance:
public enum MyEnum
{
[Description(null)]
None = 0,
[Description("X")]
MyX,
[Description("Y")]
MyY
}
You can get the description of the 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();
}
Usage:
MyEnum e = MyEnum.None;
string s2 = GetEnumDescription((MyEnum)e); // This returns null
All enum types are value types and the different members are also derived from member types (the allowed types are byte
, sbyte
, short
, ushort
, int
, uint
, long
, or ulong
- as documented).
This means that members of an enumeration cannot be null
.
One way to deal with a default enum
value is to put the None
value as the first value and setting it to a negative value (for signed enums) or 0
.
public enum MyEnum
{
[StringValue(null)]
None = -1,
[StringValue("X")]
MyX,
[StringValue("Y")]
MyY
}
You can have a null
reference to an enumeration if you declare a nullable instance - myenum?
.
There is no such thing as an "enum with a null value". An enum in C# is just 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 underlying data-type of an enum is int
, but it can also be other integer-based primitive types of different sizes/sign.
If you want a "null" enum, you would have to use MyEnum?
, aka Nullable<MyEnum>
.