Simplified switch

I commonly included this code at the end of a C# switch statement, in a misguided effort to proactively satisfy the syntax of the switch statement:

switch (contentType)
{
    case FraMES.ContentTypes.Something:
        do stuff for Something;
        break;       
    default:
        throw new Exception("FraMES.ThisMethod received an unhandled contentType: " + contentType.ToString());
#pragma warning disable 0162 //disable the compilation warning "Unreachable code detected".
        break;
#pragma warning restore 0162 // enable the compilation warning "Unreachable code detected".
}

The break; statement was to satisfy the syntax of the switch statement. However, switch recognizes the thrown exception as the end of it’s logic, and the break; statement is superfluous. This is perfectly valid and easier to read:

switch (contentType)
{
    case FraMES.ContentTypes.Something:
        do stuff for Something;
        break;       
    default:
        throw new Exception("FraMES.ThisMethod received an unhandled contentType: " + contentType.ToString());
}
This entry was posted in C#, Programming. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.