Refactoring the blindingly obvious – Enums and Value Names

I know many people have written about this one, but it’s cropped up yet again in the app I’m maintaining.  The old chestnut of setting a string based on an enum value – when the enum names are identical to the string values (most often with one word names). 



public enum ItemStatus
{
    Draft 
1,
    Pending 
2,
    Released 
3,
    Recalled 
4,
    Rejected 
5,
}


switch (item.ItemStatus)
{
    
case ItemStatus.Draft:
        {
            statusLabel.Text 
“Draft”;
            break;
        
}
    
case ItemStatus.Pending:
        {
            statusLabel.Text 
“Pending”;
            break;
        
}
    
case ItemStatus.Released:
        {
            statusLabel.Text 
“Released”;
            break;
        
}
    
case ItemStatus.Recalled:
        {
            statusLabel.Text 
“Recalled”;
            break;
        
}
    
case ItemStatus.Rejected:
        {
            statusLabel.Text 
“Rejected”;
            break;
        
}
}


//or alternatively just take the ‘name’ as a string and get rid of the switch altogether
statusLabel.Text communicationItem.CommunicationItemStatus.ToString(“g”);




Colorized by: CarlosAg.CodeColorizer

There’s other ways to do this if you want more of a ‘description’ (e.g. multiple words).  The StringEnum class could do it for you, or you could provide your own implementation with a Description attribute on the values – e.g.  [Description(“My extended value name”)]