Control Statements


Control statements define what code should run. C# defines the if and switch statements, and the conditional operator.

if Statement

The C# if statement is the same as the C++/CLI version. Visual Basic uses If-Then/Else/End If instead of curly brackets.

  // C# and C++/CLI if (a == 3) {     // do this } else {    // do that } ' Visual Basic If a = 3 Then    ' do this Else    ' do that End If 

Conditional Operator

C# and C++/CLI support the conditional operator, a lightweight version of the if statement. In C++/CLI, this operator is known as ternary operator. The first argument must result to a Boolean result; if the result is true, the first expression is evaluated; otherwise, the second one is. Visual Basic has the IIf function in the Visual Basic Runtime Library that offers the same functionality.

  // C# string s = a > 3 ? "one" : "two"; // C++/CLI String^ s = a > 3 ? "one" : "two"; ' Visual Basic Dim s As String = IIf(a > 3, "one", "two") 

switch Statement

The switch statement looks very similar in C# and C++/CLI, but there are important differences. C# supports strings with the case selection. This is not possible with C++. With C++ you have to use if-else instead. C++/CLI does support an implicit fall-through from one case to the next. With C# the compiler complains if there’s not a break or a goto statement. C# only has implicit fall-through if there’s not a statement for the case.

Visual Basic has a Select/Case statement instead of switch/case. A break is not only needed but also not possible. An implicit fall-through from one case to the next is not possible, even if there’s not a single statement following Case; instead, Case can be combined with And, Or, and To, for example, 3 To 5.

  // C# string GetColor(Suit s) {    string color;    switch (s)    {       case Suit.Heart:       case Suit.Diamond:          color = "Red";          break;       case Suit.Spade:       case Suit.Club:          color = "Black";          break;       default:          color = "Unknown";          break;    }    return color; } // C++/CLI String^ GetColor(Suit s) {    String^ color;    switch (s)    {       case Suit::Heart:       case Suit::Diamond:          color = "Red";          break;       case Suit::Spade:       case Suit::Club:          color = "Black";          break;       default:          color = "Unknown";          break;    }    return color; } ' Visual Basic Function GetColor(ByVal s As Suit) As String    Dim color As String = Nothing    Select Case s       Case Suit.Heart And Suit.Diamond          color = "Red"       Case Suit.Spade And Suit.Club          color = "Black"       Case Else          color = "Unknown"    End Select    Return color End Function 




Professional C# 2005 with .NET 3.0
Professional C# 2005 with .NET 3.0
ISBN: 470124725
EAN: N/A
Year: 2007
Pages: 427

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net