Short read: enums in place of const in c#

·

4 min read

I promise this is short read lol.

An enumeration is a distinct value type, housing a set of named constants (known as the enumerator list).

So, let's say you what to create a class called chemistry and you need to deal with certain constant temperatures such as:

const int FreezingPoint = 32; // degrees Fahrenheit
const int BoilingPoint = 212;
const int LightJacketWeather = 60;
const int SwimmingWeather = 72;
const int WickedCold = 0;

Someone reading this code may get to wonder why do we have these variables? Let's assume it's obvious hopefully, the next issue suffices: is there any logical connection at the first glance of these constants?

Does the reader go: "oh it appears Tom is trying to establish the various measured temperatures in Fahrenheit". The key has always been to make code so good, it reads like poetry.

To achieve this, we use the Enums type provided to us by c#. Enumerations have an integral type (integer, short, long, etc.) except for char. By default, the base type is of type int unless we explicitly state otherwise.

        enum Temperatures :short
        {
        WickedCold = 0,
        FreezingPoint = 32,
        LightJacketWeather = 60,
        SwimmingWeather = 72,
        BoilingPoint = 212,
        }

Temperatures serves as the identifier for this enumeration. To get the values we do this:

        enum Temperatures :short
        {
        WickedCold = 0,
        FreezingPoint = 32,
        LightJacketWeather = 60,
        SwimmingWeather = 72,
        BoilingPoint = 212,
        }

        static void Main(string[] args)
        {


            System.Console.WriteLine((short)Temperatures.BoilingPoint);

        }

To display the value of an enumerated constant, you must cast the constant to its underlying type (e.g short as we did above). The integer value is passed to WriteLine, and that value is displayed. If we did something like this:

System.Console.WriteLine(Temperatures.BoilingPoint);

//output
BoilingPoint

The above output occurs because by default an enumeration value is displayed by using its symbolic name which in this case was BoilingPoint.

Source code:

using System;
using System.Text;
using System.Collections.Generic; 
using System.Linq;
using System.IO;

namespace playground
{
    delegate void MyDelegate(int num);
    class Program
    {
        enum Temperatures :short
        {
        WickedCold = 0,
        FreezingPoint = 32,
        LightJacketWeather = 60,
        SwimmingWeather = 72,
        BoilingPoint = 212,
        }

        static void Main(string[] args)
        {


            System.Console.WriteLine(Temperatures.BoilingPoint);

        }


    }

}