Initial Value of an Enum

C#Enums

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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;}
}

Solution 3 - C#

Enum fields are initialized as zero; an if you don't specify values in an enum, they start at zero (Email = 0, SharePoint=1, etc).

Thus by default any field you do initialize yourself will be Email. It is relatively common to add None=0 for such cases, or alternatively use Nullable<T>; i.e.

/// <summary>
/// All available delivery actions
/// </summary>
public enum EnumDeliveryAction
{
    /// <summary>
    /// Not specified
    /// </summary>
    None,

    /// <summary>
    /// Tasks with email delivery action will be emailed
    /// </summary>
    Email,

    /// <summary>
    /// Tasks with SharePoint delivery action 
   /// </summary>
   SharePoint
}

You should also be sure to never treat your last expected value as a default; i.e.

switch(action) {
    case EnumDeliveryAction.Email; RunEmail(); break;
    default: RunSharePoint(); break;
}

this should be:

switch(action) {
    case EnumDeliveryAction.Email; RunEmail(); break;
    case EnumDeliveryAction.SharePoint; RunSharePoint(); break;
    default: throw new InvalidOperationException(
          "Unexpected action: " + action);
}

Solution 4 - C#

Best practice (as advised by Code Analysis) is to always have a default value in your enums, which represent an unset value.

So in your case, you might have:

public enum EnumDeliveryAction
   {

    /// <summary>
    /// Default value
    /// </summary>
    NotSet,

    /// <summary>
    /// Tasks with email delivery action will be emailed
    /// </summary>
    Email,

    /// <summary>
    /// Tasks with SharePoint delivery action 
   /// </summary>
   SharePoint
  }

As an aside, you shouldn't prefix the name of the enum with Enum. You might consider changing to:

public enum DeliveryAction;

Solution 5 - C#

Enums are value types. Value types cannot be null and are initialized to 0.

Even if your enum does not have a 0, enum variables will be initialized to 0.

public enum SomeEnum
{
    A = 1,
    B = 2
}

(later)

SomeEnum x = default(SomeEnum);
Console.WriteLine(x);

Outputs - 0


Some answerers are advocating using Nullable<T> to match your initialization expectations. Becareful with this advice since Nullable<T> is still a value type and has different semantics than reference types. For example, it will never generate a null reference exception (it's not a reference).

SomeEnum? x = default(SomeEnum?);

if (x == null)
{
    Console.WriteLine("It's null!");
}
if (x > SomeEnum.B)
{
}
else
{
    Console.WriteLine("This runs even though you don't expect it to");
}

Solution 6 - C#

You can start your enums at any value (such as 1), but when they represent a lookup value in a Database, you generally want them to match up.

I generally declare the first Enum as None ( = 0) when it makes sense to do so, as per the .Net Framework Design guidelines.

Solution 7 - C#

The traditional aproach to adding a null to values that don't generally have one is to declare your variable as a nullable type, ie:

EnumDeliveryAction? action=null;

Solution 8 - C#

I'd suggest having a value of None = 0 as your first enum value. Make it explicit, then you know for sure what it's value is.

Solution 9 - C#

By default only reference types are nullable types. If you want a variable to allow nulls you have to define it as nullable using the "?" character (for this you need C# 2.0 or up).

enum MyEnum
{
    ValueOne,
    ValueTwo
}

and in your class

MyEnum? myvariable = null;

Solution 10 - C#

My C++ teacher in college (11 years ago) told me that the linker replaces enum with their actual type:

typedef static const int enum;

Thus, any time you write something like enum MY_VAL = 5;, you could easily replace with static const int MY_VAL = 5; (but that just makes your code longer...).

Anyway, the default value of any int is 0.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJL.View Question on Stackoverflow
Solution 1 - C#mmxView Answer on Stackoverflow
Solution 2 - C#Josh KodroffView Answer on Stackoverflow
Solution 3 - C#Marc GravellView Answer on Stackoverflow
Solution 4 - C#Winston SmithView Answer on Stackoverflow
Solution 5 - C#Amy BView Answer on Stackoverflow
Solution 6 - C#Mitch WheatView Answer on Stackoverflow
Solution 7 - C#BlindyView Answer on Stackoverflow
Solution 8 - C#BCarterView Answer on Stackoverflow
Solution 9 - C#monkey_pView Answer on Stackoverflow
Solution 10 - C#SsJVastoView Answer on Stackoverflow