I have a class with a property which is an enum
The enum is
/// <summary> /// All available delivery actions /// </summary> public enum EnumDeliveryAction { /// <summary> /// Tasks with email delivery action will be emailed /// </summary> Email, /// <summary> /// Tasks with SharePoint delivery action /// </summary> SharePoint }
When I create an instance of this class, NOWHERE in the code, do I specify the value of the enum field, but it seems to default to the first item in the enumlist, and not a null value, is this how enums work? How is it possible to ensure that the enum gets some kind of null value if it is not set, I don't want it defaulting to the first value in the enum.
The first member of an enum will be 0, and the value of each successive enum member is increased by 1. You can assign different values to enum member. A change in the default value of an enum member will automatically assign incremental values to the other members sequentially.
The default for one who holds a reference to an enum without setting a value would be null (either automatically in case of a class field, or set by the user explicitly).
You can't create an instance of Enum using new operators. It should have a private constructor and is normally initialized as: ErrorCodes error = ErrorCodes. BUSSINESS_ERROR. Each constant in the enum has only one reference, which is created when it is first called or referenced in the code.
By default, the value of the first enumerator is zero if it is implicitly defined. The value of each subsequent implicitly-defined enumerator is the value of the previous enumerator + 1. (Optional) The name of a variable of the enumeration type.
Default value for enum
types is 0
(which is by default, the first element in the enumeration). Fields of a class will be initialized to the default value.
If you need to represent an unknown value in the enum, you can add an element Unknown
with value 0. Alternatively, you could declare the field as Nullable<MyEnum>
(MyEnum?
).
Enums are a value type, like ints. You need to make it nullable so as not to default to the first (or 0-defined) enum member.
public class MyClass { public EnumDeliveryAction? DeliveryAction { get; set;} }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With