Enums and properties of enums in C#

Goud.Kv
Posted by in C# category on for Beginner level | Points: 250 | Views : 6149 red flag

C# is an Object-oriented programming language. C# comes with simplicity, expressiveness and great performance to meet the programmer productivity.

Introduction

So far, we have seen about interfaces and re-implementing interfaces in C#. Now let's get into the new topic of enums in C#.

Objective

The main objective of this article is to learn about enums in C# with examples.

Enum

Enum is to declare enumeration which uses enum keyword. It is a special value type used to specify the group of named numeric constants. These set of constants are called as enumerator list.

In the normal scenarios, we used to place the constants directly where we are using them. This increases the complexity of our program and they are very hard to change. But we can separate these constants by using enum's.

Example,
public enum MyEnum
{
    const1, const2, const3     // constants 
}
We can use this enum as,
MyEnum con = MyEnum.const1;
bool isCon = (con == MyEnum.const1);
Console.WriteLine(isCon);      // prints true
The above code will prints true in your console.

By default, underlying values of enum are of type int. The first enum member has the value 0 by default and will be increased by 1 for next successive enum members. Example,
public enum Colors {Red, Green, Blue};
In the above example, default values are Red = 0, Green = 1 and Blue = 2. We can use initializers to change the default values. Such as,
public enum Colors {Red = 2, Green, Blue};
This will starts the series from 2.
We can also specify the alternate integral types as below,
public enum Colors : byte {Red, Green, Blue};
enum can access byte, short, int, long, sbyte, ushort, uint and ulong types.

We can also declare an underlying values to the enum members explicitly like below,
public enum Colors : byte {Red = 4, Green = 6, Blue = 8};
Example:
Let's have a clear example that explain enums
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Example
{
    class Program
    {
        public enum Box
        {
            length, breadth, height
        }

        static void Main()
        {
            Box len = Box.length;
            bool isLen = (len == Box.length);
            Console.WriteLine(isLen);

            Box brd = Box.breadth;
            bool isBrd = (brd == Box.breadth);
            Console.WriteLine(isBrd);

            Box hgt = Box.height;
            bool isHgt = (hgt == Box.height);
            Console.WriteLine(isHgt);
        } 
    }
}
In the above code, we have enum with three parameters length, breadth and height. In the main method, we are creating instances like we did for classes and structs.

This code will checks the bool conditions and prints the following output,


Flags

We can also perform combining operations between enum members by using bit-wise operators such as "|" and "&" etc.
Flags are used to assign multiple values to the enum by using bit-wise operations.

Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Example
{
    class Program
    {
        [Flags]
        public enum Box
        {
            No = 0, LeftSide = 1, RightSide = 2, TopSide = 4, BottomSide = 8
        }

        static void Main()
        {
            Box lr = Box.LeftSide | Box.RightSide;

            if ((lr & Box.LeftSide) != 0)
            Console.WriteLine("Left is present");    // prints left is present

            string clr = lr.ToString();

            Box l = Box.LeftSide;
            l |= Box.RightSide;
            Console.WriteLine(l == lr);              // prints true

            l ^= Box.RightSide;
            Console.WriteLine(l);                    // prints LeftSide
        } 
    }
}
In the above example, we have an enum Box with five parameters No, LeftSide, RightSide, TopSide and BottomSide.
Observe that we have used [Flags] attribute to the enum. This will let us to perform multiple value operations that we did in the Main method of the above code.

Now press Ctrl + F5 to see the following lines in your console,


Operators

enums support and can work with arithmetic, bit-wise and comparison operators. They are -, +, ^, &, |, ~, +=, -=, ++, --, <, >, <=, >=, =, ==, !=, sizeof.

We cannot do addition between two enums as it is permitted between an enum and an integral type. i.e,
Box lr = Box.LeftSide + Box.RightSide;  // Compile time error
Box lr = Box.LeftSide + 5;  // This is valid expression

Conclusion

In this article, we have seen enums with examples. Hope you have understand it.

Thanks for reading.

Regards,
Krishna.

Recommendation
Read Enums debugging and Nested types in C# after this article.
Page copy protected against web site content infringement by Copyscape

About the Author

Goud.Kv
Full Name: Krishna Vamshi Goud
Member Level: Gold
Member Status: Member,MVP
Member Since: 2/12/2014 2:34:09 AM
Country: India
Thanks & Regards, Krishna


Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)