JonYates's Random Writings

Sponsors

Tags

No tags have been created or used yet.
Posted: by

Comments

Sam said:

I think a switch is more about code readability than functionality. I use it whenever I have more than one elseif to improve the readability of my code.

That's all a switch is good for!!!
# March 23, 2004 1:01 PM

Eric Lippert said:

Of course, the only answer is "it depends on the situation".

A switch is just like what it sounds -- imagine a knob with five positions, you switch it to one of them. An "if" is just like what it sounds -- you have a condition, you evaluate its truthfulness, you do the appropriate consequences.

Which you choose depends on which situation you find yourself in.

A third option often overlooked is to have table-driven logic rather than statement-driven logic. Often See my article here:

http://blogs.msdn.com/ericlippert/archive/2004/02/24/79292.aspx
# March 23, 2004 2:19 PM

Suman Chakrabarti said:

I remember hearing once that in VB6-- if statements were faster than select statements but select statements were for easier readability.

I doubt there is a performance difference in managed code, but they certainly are a plus.

Maybe one of the benefits is the fact that you can fall through several cases whereas with an if..else you break immediately. For example:

switch (SecurityLevel)
{
case Administrator:
Console.WriteLine("I'm an Administrator");
case Moderator:
Console.WriteLine("I have Moderator rights");
break;
case User:
Console.WriteLine("I'm only a user");
break;
}

That's probably the only benefit other than readability
# March 23, 2004 3:48 PM

Johnny Hall said:

Someone posted a couple of days ago about this very subject. Can't remember who, but the upshot was that the switch was faster than the ifs.

The surmise was that the jitter optimised the heck out of the switch.

Sorry I can't remember who posted it. It was in response to something on Darren Neimke's blog.
# March 23, 2004 5:20 PM

TrackBack said:

^_^,Pretty Good!
# April 9, 2005 11:56 PM

Developer said:

JonYates's Randon writings or JobYates's Mindless Writings ... y wasting urs and others time doing so?
# May 2, 2006 4:21 PM

Jon said:

Fascinating feedback, do you mind expanding on what you feel was a waste of time?
# May 3, 2006 6:15 AM