Console C#.Net Tutorial

Visual Studio.NET IDE

Define C#.NET

C# Comment

C# Variables

C# Data Types

C# Escape Sequence

C# Operators

Format String

Operator Precedence

C# Keywords

Constant Variable

Type Conversion

Flow Control

C# Arrays

C# Character

C# Strings

User-Define Methods

Variable Scope

C# Enumerations

C# Structure

C# Exception Handling

Object Oriented Programming

C# Classes

Constructor & Destructor

C# Inheritance

C# Polymorphism

C# Operator Overloading

C# Method Overriding

C# Interface

Abstract Classes & Methods

Sealed Classes, Methods

C# Properties

C# Indexer

C# Delegates

C# Generics

C# Collection

C# ArrayList

C# Stack

C# Queue

C# HashTable

C# SortedList

Page Stats

Visitor: 210

C#.Net Enumerations

Enumerations are special value data type, in which names are mapped with the numbers, usually integers. The enum keyword is used to declare an enumeration. enum can be declared inside or outside a class or structure.

Syntax:

enum variable_name
{
    value1,
    value2,
    value3,
    ...
}

Example 1: Program to declare enum value and write in console

namespace ConsoleApplication1
{
    public enum WeekDays { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }
    
    class Program
    {
        static void Main(string[] args)
        {
            WeekDays day = WeekDays.Monday;
            Console.WriteLine((int)day); 
            //An explicit type casting is necessary to convert enum type to integer type. 
            Console.ReadLine();
        }
    }
}

By default, the first member of an enum has the value 0 and the value of each successive enum member is increased by 1. In the above example, enumeration, Monday is 0, Tuesday is 1, Wednesday is 2 and so on.

Advertisement

Example 2: Program with specifying enum value.

namespace ConsoleApplication1
{
    enum WeekDays : int  { Monday =10, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine((int) WeekDays.Tuesday );
            Console.Read();
        }
    }
}

A change in the value of the first enum member will automatically assign incremental values to the other members sequentially. For example, changing the value of Monday to 10, will assign 11 to Tuesday, 12 to Wednesday, and so on:

Enum uses numberic data type eg. sbyte, byte, short, ushort, int, uint, long, or ulong. Decimal, String data types cannot be used.

Enum Methods: GetName, GetNames

GetName: Returns the name stored inside enum at specified value.

GetNames: Returns an array of string name of all specified enum.

Example 3: GetName, GetNames. add the below code in example 1.

Console.WriteLine(Enum.GetName(typeof(WeekDays), 2)); //Wednesday
	
foreach (string str in Enum.GetNames(typeof(WeekDays)))
    Console.WriteLine(str);
Updated: 28-Aug-21