C Sharp

No Fall-Through in switch Statements

Throughout the design phase of C#, its designers were cognizant of applying a "risk/reward" test when deciding whether a feature should be included in the language. The fall-through feature is an example of one that didn't pass the test. Normally in C++, a case statement runs when its constant-expression matches the switch_expression. The switch statement is then exited with a break statement. Fall-through causes the next case statement in the switch statement to execute in the absence of a break statement.

Though not supported in C#, fall-through is typically used in situations in which you have two case labels and the second label represents an operation that will be done in either case. For example, I once wrote a database editor in C++ that allowed end users to create their tables and fields graphically. Each of these tables was displayed in a tree view in a Windows Explorer"like user interface. If the end user right-clicked the tree view, I wanted to display a menu with options such as Print All Tables and Create New Table. If the end user right-clicked a specific table, I wanted to display a context menu for that table. However, that menu also needed to include all the tree view options as well. Conceptually my code was similar to the following: -

// Dynamically create menu in C++.
    case TABLE:
    // Add menu options based on current table;
    // break left out intentionally.
    case TREE_VIEW:
    // Add menu options for tree view.
// Display menu.

The first case label amounts to a combination of the two labels without me having to duplicate code or insert two calls to the same method. However, the C# language designers decided that although this feature can be handy, its reward wasn't worth the risk involved because the majority of the time a break statement is left out unintentionally, which results in bugs that are difficult to track down. To accomplish this in C#, you'd probably be better off using an if statement instead: -

// Dynamically create menu.
if (itemSelected == TABLE)
    // Add menu options based on current table.
// Add menu options for tree view.
// Display menu.

Iteration Statements

In C#, the while, do/while, for,and foreach statements enable you to perform controlled iteration, or looping.

In each case, a specified simple or compound statement is executed until a Boolean expression resolves to true, except for the case of the foreach statement, which is used to iterate through a list of objects.

by BrainBellupdated