Use Enumerator power instead of doing infinite if/else
Posted by Nordes on August 17th, 2008 filed in C#, ProgrammingWhile working with C# I found out that we can easily use the power of “Enum” instead of using hard-coded stuff. As many of you know, when we are posting a page using a query string the other page may want to manage it efficiently. Some people are doing multiple if/else to only validate the string passed in the query string. When you have the wrong case, or when it does not exist in your if/else statement, you may encounter some bugs. Instead of that, you can use simple enumerator and also have a default value or even throw an exception when it does not exist.
You first need to create your enum if it doesn’t already exists in your actual project:
1 2 3 4 5 6 | private enum MyEnum { POSSIBLE_VALUE_1 = 1, POSSIBLE_VALUE_2 = 2, DEFAULT_VALUE = 1 } |
After, in your page load or wherever you need it, you can do as follow to convert your string to your enum. That way, it will be more useful inside your project.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | MyEnum test; try { test = (MyEnum)Enum.Parse(typeof(MyEnum), Request.QueryString["MyQueryStringItem"].ToString(), true); } catch (Exception) { // Possible exception: // The query string does not exist : NullReferenceException // The query string value is not in the enum: ArgumentException test = MyEnum.DEFAULT_VALUE; // Or you can throw your own exception here. } |
You now see how easy it is to convert a simple string to an enum type. After that conversion, it will be more usable across your project. You will also be able to do switch with a more robust case. In case you change your enum list and you remove an item. At compile time, it will tell you that the enum value selected does not exists. That way your code stay clean.
October 25th, 2009 at 11:21 pm
aware exploded mouse generalists idiots coloney richmediacbs privateering specifically vknsk typical factual
October 29th, 2009 at 3:10 pm
june addiction mince draft monies crosshair meena selecting interior density ubos