1. Computing

C# Enum Programming Tip

By March 12, 2013

Follow me on:

Did you know that enums in C# can have their underlying type specified? It has to be an int type, and only one of a few types, if you try to use a type like System.UInt16 you get a error Type byte, sbyte, short, ushort, int, uint, long, or ulong expected.

This short example shows the difference in size between the shortest and longest enum types.

using System;

namespace ex1
{
    class Program
    {
        private enum colbyte : byte {redbyte,yellowbyte,greenbyte};
        private enum col : ulong{ red,yellow,green};

        static void Main(string[] args)
        {
            Console.WriteLine("Size of colbyte = {0} col = {1}",sizeof(colbyte) ,sizeof(col)) ;
            Console.ReadKey() ;
        }
    }
}

It outputs: Size of colbyte = 1 col = 8. It's probably not that useful but if you have a large number of objects and want to keep the space down, specifying a byte might prove useful.

Comments
Comments are closed for this post.
Leave a Comment

Line and paragraph breaks are automatic. Some HTML allowed: <a href="" title="">, <b>, <i>, <strike>

©2014 About.com. All rights reserved.