Sep 20, 2011

Array of enum in C#

Array of enum means array which contains only symbolic constants of that enum.

using System;

namespace arrayDemo
    class Program
        enum Color { Red, Green, Blue };
        static void Main(string[] args)
            Color[] arr = new Color[3];

            arr[0] = Color.Green;
            arr[1] = Color.Red;
            arr[2] = Color.Blue; 

            //printing value of each element in the array
            foreach (int element in arr)

In the above example array of enum arr can keep only Color.Red, Color.Green and Color.Blue

For any other value we have first type cast into Color. For example:
arr[0] = (Color)5;

No comments: