How to create an enumeration of constants with and without explicit values in C#

3 Answers

0 votes
using System;

class Program
{
    enum EN {Dog, Cat, Rabbit, Parrot};


    static void Main()
    {
        EN c = EN.Cat;
        if (c != EN.Dog)
          Console.WriteLine(c + " = " + (int)c);    
    }
}



/*
run:

Cat = 1

*/

 



answered Mar 24, 2019 by avibootz
0 votes
using System;

class Program
{
    enum EN {CSharp = 23, C = 43, PHP = 56, Python = 98};

    static void Main()
    {
        Console.WriteLine((int)EN.PHP);   
        Console.WriteLine(EN.PHP);     
    }
}



/*
run:

56
PHP

*/

 



answered Mar 24, 2019 by avibootz
0 votes
/* 
   Title: Enumeration of Constants in C#
   Example with and without explicit values
*/

using System;

// Enum WITHOUT explicit values
// C# automatically assigns 0, 1, 2...
enum Color
{
    Red,    // 0
    Green,  // 1
    Blue    // 2
}

// Enum WITH explicit and mixed values
enum Status
{
    OK = 1,        // 1
    Warning = 5,   // 5
    Error,         // 6 (auto: previous + 1)
    Critical = 10  // 10
}

class Program
{
    static void Main()
    {
        Console.WriteLine("Enum without explicit values:");
        Console.WriteLine("Red = " + (int)Color.Red);
        Console.WriteLine("Green = " + (int)Color.Green);
        Console.WriteLine("Blue = " + (int)Color.Blue);

        Console.WriteLine("\nEnum with explicit and mixed values:");
        Console.WriteLine("OK = " + (int)Status.OK);
        Console.WriteLine("Warning = " + (int)Status.Warning);
        Console.WriteLine("Error = " + (int)Status.Error);
        Console.WriteLine("Critical = " + (int)Status.Critical);
    }
}


/* 
run:

Enum without explicit values:
Red = 0
Green = 1
Blue = 2

Enum with explicit and mixed values:
OK = 1
Warning = 5
Error = 6
Critical = 10

*/

 



answered 5 hours ago by avibootz

Related questions

...