Programming several conditions in C#

Programming several conditions in C#

When you have to programme a piece of code which have several conditions you could do it in the following way:

switch(a.name)
{
    case "smith":
        CallHim();
       
break;
    case "doyle":
        SendAMessageToHim();
        break;
    default:
        throw new WriteNotReachableErrorException();
}

If you couldn’t use constants as conditions, you will implement the logic in the following way:

if(a.name == smithObject.ToString())
{
    CallHim();
}
else if(a.name == doyleObject.ToString())
{
    SendAMessageToHim();
}
else
{
    throw new WriteNotReachableErrorException();
}

But if you think now there is now other possibility to implement the logic, wait! I found recently following code which is doing exactly the same thing:

for(;;)
{
    if(a.name == smithObject.ToString())
    {
        CallHim();
        break;
    }
    if(a.name == doyleObject.ToString())
    {
        SendAMessageToHim();
        break;
    }
    throw new WriteNotReachableErrorException();
}

I’m not sure if the last version is comprehensible and maintainable. I will go even further, it’s bad code, because there are better constructs (else if) for doing the job, so we don’t need an approximation workaround for the switch-case statement.

Leave a Reply

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