Posts Tagged ‘tricks of the trade’

Trick of the trade – set enum to not zero

July 5th, 2016

When defining enums set the first of the items to a non-zero value.
This way one knows whether one has forgotten to set the value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using System;
                   
public class Program
{
    private static int SomeNonInitiatedValueFromSomewhere = 0;
   
    public enum MyEnum
    {
        AnItem = 1,
        AnotherItem
    }
   
    public static void Main()
    {
        var myEnum = MyEnum.AnotherItem;
        MyEnum myForgottenEnum = (MyEnum)SomeNonInitiatedValueFromSomewhere;
           
        Console.WriteLine("Now={0}", DateTime.Now.ToString("HH:mm"));
       
        Console.WriteLine("myEnum={0}", myEnum); // This enum is set.
       
        Console.WriteLine("myForgottenEnum={0}", myForgottenEnum); // This enum is not set.
    }
}

from https://dotnetfiddle.net/17tQMB