"enum" keyword in C-Sharp

The "enum" keyword is used to declare an enumeration, a distinct type consisting of a set of named constants called the enumerator list. Every enumeration type has an underlying type which can be any integral type except char.
  • 2223

Introduction

The "enum" keyword is used to declare an enumeration, a distinct type consisting of a set of named constants called the enumerator list. Every enumeration type has an underlying type which can be any integral type except char. The default underlying type of the enumeration elements is int. By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1. The "enum" Keyword is of Value Type. It is used to define integral constant and literals. It is inherited from the base class library(BCL)  'Enum' where Enum's static methods are used by enum type for parsing enum values. This article tries to cover some of the enum functionality through code demonstration. Below is the source code which highlights various enum methods that are useful during the development phase.

Enums store special values and make programs simpler. If you place constants directly where used your C#  program rapidly becomes complex and hard to change. Enums instead keep these magic constants in a distinct type. This improves code clarity and alleviates maintenance issues.

Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace @enum
{
    class Program
    {
        enum Importance
        {
            None,
            Trivial,
            Regular,
            Important,
            Critical
        };
        static void Main(string[] args)
        {
            Importance value = Importance.Critical; 
            if (value == Importance.Trivial)
            {
                Console.WriteLine("Not true");
            }
            else if (value == Importance.Critical)
            {
                Console.WriteLine("True");
            }
            Console.ReadLine();
        }
    }
}

Output 

 Clipboard04.gif

© 2019 DotNetHeaven. All rights reserved.