Saturday, May 9, 2009

Explain enum in c# programming,code,usage &...?

An enum is a way to group together a bunch of related constants of which the values (often) don't really matter --the important thing is that you're talking about DIFFERENT values that need to identified.





For example, I'm writing a program in which reviews are stored about DVD's, CD's and books. To identify the type of review, I'm using an enum:





enum ReviewType { None, DVD, CD, Book };





Whenever I need to store the type of the objct I'm reviewing, I don't need to use constant numbers (0, 1, 2, 3, ...) but I can use meaningful constants instead, making the code much easier to read:





switch (thisObject.ReviewType)


{


  case ReviewType.DVD: // Reviewing a DVD!


  .


  .


  break;





  case ReviewType.CD: // Reviewing a CD!


  .


  .


  break;





  case ReviewType.Book: // Reviewing a Book!


  .


  .


  break;





  default: // You forgot to initialize thisObject's ReviewType!


  .


  .


  break;


}





The advantage is, again, that it documents your code without actually having to put comments in the code (wouldn't the code above be just as understandable without the remarks?) without any loss of performance. Also: you get type checking for free, because even though all enums are translated into integers, they do all get a different type, so you can't assign one to another without some type of cast --so it makes your code a lot 'safer'.





I hope that helps!


No comments:

Post a Comment