Today in the world of Rapid Application Development .NET is a rich tool having large extent of flexibility, but while programming we need to take care of certain things so that our code can not loose this flexibility.
I have seen many skilled developers who are willing to use switch case but they usually like to use it in such a manner that in future it become useless, I mean if they require some modification then it will become a difficult task.
Whenever there is requirement of switch case we need to be sure of datatype involved and the range of value. If we get this picture in our mind than it will become easy to enhance switch case through enumeration. Lets understand it with an example:
I have a car object and I'm retrieving cars color from database which is integer value 0,1,2 . Now I need to show car's color.So I have created an enumeration with name CarColor.
enum CarColor
{
RED = 0,
BLACK = 1,
WHITE = 2
}
Now I will create a function which will decide the car color and return me the color of car.
private string ShowCarsColor(int dbcarcolcode)
{
switch (dbcarcolcode)
{
case CarColor.RED:
return cstr(CarColor.RED);
case CarColor.BLACK:
return cstr(CarColor.BLACK);
case CarColor.WHITE:
return cstr(CarColor.WHITE);
default:
return "Invalid Color";
}
}
Well ,I have to simply call it and I will get the desired result. Now you will ask what's new with it,So let me point out those things:
*Readability - Because I have already documented my code
*Few No. of lines of code- I have saved many lines of code
*Flexibility and scalability - If you want to add more colors in future ,Of course you can and I'm sure in a easy way.
So why should not we try it have a try.
-
If you are aware of best usages of switch case then feel free to post your valuable comments.
Shallow copy and deep copy in .NET
-
*A shallow copy creates a new instance of the same type as the original
object, and then copies the nonstatic fields of the original object. If the
field i...
16 years ago

No comments:
Post a Comment