Monday, April 28, 2014

Enum with char values


We all use enums in our code to define a small subset of values so that our code can be strong typed. Take an example, the following is a small enum:
 
public enum Status : int
    {
       Active,
       Inactive
    }
 
We can assign them integer values if so desired
 
public enum Status : int
    {
       Active = 0,
       Inactive = 1
    }
 
 
But some time, when you do debugging in different app domain, all you get is an integer values, it may not be intuitive enough. We would like to have something like:
 
    public enum Status : String
    {
       Active = “A”,
       Inactive = “I”
    }
 
 
In another word, we want to give enum string values instead of integer values. Well,  there is something close to what we ask for, but not there yet.
 
 
Since Visual Studio 2010, in C#, you can defined enum like the following :
 
    public enum Status : int
    {
       Active = 'A',
       Inactive = 'I'
    }
 
 
With this definition, you do get to assign character value to each of enum values. It looks very promising. But be caution, if you do not proceed with care, you might run into problem without noticing them.  Take a look at the following unit tests:
 
 
  [TestMethod]
        public void TestMethod1()
        {
            var myStatus = Status.Active;
            Assert.AreEqual('A', (char)myStatus);
            Assert.AreNotEqual('A', myStatus);
            Assert.AreNotEqual(0, myStatus);
            Assert.AreEqual(65, (int)myStatus);
            Assert.AreEqual("Active", myStatus.ToString());
            Assert.AreEqual("A", ((char)myStatus).ToString());
        }
 
 
 
What these test case means are :
 
  1. If you cast the enaum to char you get the char value
  2. If you just directly compare the enam value with the char value, you will find they are different.
  3. It is not taking the default value starting from zero either
  4. But it does have a integer value.  For example 65 is the ASCII value of ‘A’, so myStatus.Active is having integer value of 65 and myStatus.Inactive is have integer value of 73.
  5. If you want to get the string value of “A” or “I”, you need to cost it to Char and then do ToString() on it.
  6. However, if you do ToString on the enum value, you still get the name of the enaum value as it does on other traditional enums.
  7. the bottom line is when you assign char value to an enum value, it assign the Hex value of the char to it. it then can be converted to the respective decimal value of it.
 
 
 
Not a big deal in architecture aspect, but it does help to make your code clearer and neater, more importantly, more intuitive when you work with the data aspect of your problem…
 
Again, please use it with caution.
 
 
 
Happy enuming.
 

No comments:

Post a Comment