Monday, December 8, 2008

C# enums and aliases - weird behaviour

Jon has been playing with enum values, and fond some apparently inconsistent behaviour from the compiler.

Notes from this example:

  • If you’re going to set an enum value, set all of them.

  • If the value aligns to a table or values used in the database, always set all of the values in the enum.

Also, notice how TestA becomes an alias of TestB, yet TestE becomes an alias of TestD, see how this appears to be reversed.

I was quite surprised with this but it seems it has something to do with TestB being set prior to TestE being set.



using System;
namespace TestConsoleApp
{
   class Program
   {
      enum TestType
      {
         TestA, // TestA is an alias of TestB
         TestB = 0,
         TestC,
         TestD,
         TestE = 2, // TestE is an alias of TestD
         TestF,
         TestG = 6,
         TestH
      }
 
      static void Main(string[] args)
      {
         TestType dc1 = TestType.TestB;
 
         if (dc1 == TestType.TestA)
         
            // since TestA is just an alias to TestB this works.
            Console.WriteLine("No compile warning is bad.");
         }
 
         int a = (int)TestType.TestA; // alias of TestB
         int b = (int)TestType.TestB;
         int c = (int)TestType.TestC;
         int d = (int)TestType.TestD;
         int e = (int)TestType.TestE; // alias of TestD
         int f = (int)TestType.TestF;
         int g = (int)TestType.TestG;
         int h = (int)TestType.TestH;
 
         Console.WriteLine("{0} - {1}"TestType.TestA, a); // Prints 'TestB – 0'
         Console.WriteLine("{0} - {1}"TestType.TestB, b); // Prints 'TestB – 0'
         Console.WriteLine("{0} - {1}"TestType.TestC, c); // Prints 'TestC – 1'
         Console.WriteLine("{0} - {1}"TestType.TestD, d); // Prints 'TestD – 2'
         Console.WriteLine("{0} - {1}"TestType.TestE, e); // Prints 'TestD – 2'
         Console.WriteLine("{0} - {1}"TestType.TestF, f); // Prints 'TestF – 3'
         Console.WriteLine("{0} - {1}"TestType.TestG, g); // Prints 'TestG – 6'
         Console.WriteLine("{0} - {1}"TestType.TestH, h); // Prints 'TestH – 7'
         Console.WriteLine();
 
         TestType type = (TestType)Enum.Parse(typeof(TestType), "TestA");
         Console.WriteLine("{0} - {1}", type, (int)type); // Prints 'TestB – 0'

 
         Console.ReadKey();
      }
   }
}




No comments: