Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initial Value of an Enum

Tags:

c#

enums

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.

like image 989
JL. Avatar asked Jul 22 '09 13:07

JL.


People also ask

Do enum values start at 0 or 1?

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.

What is the default value of enum in Java?

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).

Can enum be initialized?

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.

What is the default value of enum in C++?

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.


2 Answers

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?).

like image 81
mmx Avatar answered Sep 17 '22 18:09

mmx


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;} } 
like image 28
Josh Kodroff Avatar answered Sep 18 '22 18:09

Josh Kodroff