Freelance Writing Jobs | Today's Articles | Sign In

 
Browse Sections

Branching in C#


Many programmers who are coming from C/C++ will need to adjust to how C# handles the switch statement. At first glance both languages seem to be the same, but they are not. The following is an example of a switch statement in C#.

Listing 3
class Example {
public static Main() {

int nType;
nType = 100;
switch ( nType )
{
case 10:
System.Console.WriteLine("Type is 10.\n");
break;
case 20:
System.Console.WriteLine("Type is 20.\n");
break;
case 50:
System.Console.WriteLine("Type is 50.\n");
break;
case 100:
System.Console.WriteLine("Type is 100.\n");
break;
default:
System.Console.WriteLine("Unknown type.\n");
break;
}
}
}

In C/C++, the switch statement has a fall through feature. What does this mean? Taking our previous example and given our scenario, if we take out the break statement for 10, and we set nType to equal 10. If we executed the code in C++, it is expected that both codes in case 10 and case 20 will be executed. The story is different for C#. In fact, the C# compiler will not compile the code.

To achieve the same flow-through effect in C#, you would have to employ the services of the goto command. Beware that this may cause your code to be unreadable later on. Not advisable if you are writing a very complex system.

In C#, you can have a switch statement like the following:

switch ( nType )
{
case 10:
case 20:
System.Console.WriteLine("Hello there.\n");
break;
default:
System.Console.WriteLine("Nothing to do.\n");
break;
}

Finally, the switch statement has an excellent support for the string object. Have a look at the following:

Listing 4
class example {
public static void Main() {
string name = "John";
switch ( name )
{
case "Matthew":
System.Console.WriteLine("Hello Matthew!\n");
break;
case "Mark":
System.Console.WriteLine("Hi there Mark!\n");
break;
case "Luke":
System.Console.WriteLine("Welcome Luke!\n");
break;
case "John":
System.Console.WriteLine("How are you John?\n");
break;
default:
System.Console.WriteLine("I don't know you!\n");
break;
}
}
}

Yes, this is reality check. This is a C# code!

Copyright © 2001 Jose Aniceto

The copyright of the article Branching in C# in C# Programming is owned by Jose Aniceto. Permission to republish Branching in C# in print or online must be granted by the author in writing.

Go To Page: 1 2

Articles in this Topic    Discussions in this Topic