Branching in C#


© Jose Aniceto

It seems that the programming industry is fond of botanical terms. If you've been programming for a while, you would have surely come across some references made about trees, branches and root. This article is a small contribution to the world of plant terms used in programming.

A computer executes a program in a sequential manner. It would take a command or statement from the program, execute it, and then move to the next instruction. The ability of computers to make decisions based on certain conditions is a powerful feature and it what makes computers intelligent and smart devices.

Branch statements in C# allows the programmer to control the flow of the program. The first branching statement we will look at is the if command and its variations. We've used if statements in previous articles and if you've programmed in C/C++ before, then the if statement should look familiar. Listing 1 is an example of an if/if-else statement in C#.

Listing 1
class Example {
public static Main() {

int nType;
nType = 100;

if ( nType == 10 ) {
System.Console.WriteLine("Type is 10.\n");
}
else if ( nType == 20 ) {
System.Console.WriteLine("Type is 20.\n");
}
else if ( nType == 50 ) {
System.Console.WriteLine("Type is 50.\n");
}
else if ( nType == 100 ) {
System.Console.WriteLine("Type is 100.\n");
}
else {
System.Console.WriteLine("Unknown type.\n");
}
}
}

The next command may come as a surprise to most of you. Well, it was for me anyway. I was surprised to find out that C# has a goto command. So why would a modern, object-oriented language support a goto command? One reason I can think of is that Microsoft has decided to include a goto command in C# is to make the migration of Visual Basic programs a lot easier. There might be other reasons why goto was included but I guess goto is a command that we have to cherish for a while.

To use the goto command, you need to first define a label. A label is simply an identifier within your program to help the compiler know where to jump to within the code. The following code illustrates a goto statement and a label.

The purpose of Listing 1 is to show how to use goto statements and to illustrate a good example of how to write a bad C# program.

Go To Page: 1 2


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

Post this Article to facebook Add this Article to del.icio.us! Digg this Article furl this Article Add this Article to Reddit Add this Article to Technorati Add this Article to Newsvine Add this Article to Windows Live Add this Article to Yahoo Add this Article to StumbleUpon Add this Article to BlinkLists Add this Article to Spurl Add this Article to Google Add this Article to Ask Add this Article to Squidoo