Using Enums for comparing string values in Switch

Posted by kaleidoscope on Geeks with Blogs See other posts from Geeks with Blogs or by kaleidoscope
Published on Mon, 13 Dec 2010 12:51:27 GMT Indexed on 2010/12/13 13:09 UTC
Read the original article Hit count: 217

Filed under:

Problem Scenario:

There is an enum keeping track of operations to be performed on a table

Public Enum PartitionKey {
Createtask,
Updatetask,
Deletetask
}

User is entering the value for the operation to be performed and the code to check the value entered in switch case.

Switch (value)

         case PartitionKey.Createtask.ToString():
         {
         Create();
         break;
         }
         case PartitionKey.Updatetask.ToString():
         { 
         Update(); 
         break;
         }
         case PartitionKey.Deletetask.ToString():
         { 
         Delete();
         break;
         }
}
and it displays as error as “.”

Solution: One of the possible implmentation is as below.

Public Enum PartitionKey: byte {
Createtask,
Updatetask,
Deletetask
}
Switch ((PartitionKey)(Int32.Parse(value)))
{
         case PartitionKey.Createtask:
         {
                  Create();
                  break;
         }
         case PartitionKey.Updatetask:
         { 
                  Update();
                  break;
         }
         case PartitionKey.Deletetask:
         { 
                  Delete();
                  break;
         }
         default:
         {
                  break;
         }
}

© Geeks with Blogs or respective owner