VB.NET to C# – 04
Making decisions

VB.NET to C# – 04
Making decisions

Making decisions is one of the most executed tasks when writing business logic. In Visual Basic .NET you use in most cases an If .. Then .. Else statement or a Select Case statement. In C# there is no big difference, beside the fact that the naming of the keywords is a bit deviant. Let’s start with a simple If .. Then ... Else statement:

Dim value1 = 3
Dim value2 = 2

If value1 > value2 Then
    ' ...
Else
    ' ...
End If

var value1 = 1;
var value2 = 2;

if(value1 > value2)
{
    // ...
}
else
{
    // ...
}

As you can see… not much different. Please note that you put the expression in C# between parentheses ‘()’ and write the keywords in lower case. And – of course – use curly braces ;-). An If .. Then ... Else statement with an extra decision statement is not very different and needs no extra explanation I assume.

If value1 > value2 Then
    ' ...
ElseIf value2 > value3 Then
    ' ...
Else
    ' ...
End If

if (value1 > value2)
{
    // ...
}
else if(value2 > value3)
{
    // ...
}
else
{
    // ...
}

The use of a Select Case statement is actually more deviant. First, in C# this keyword is called switch. Another difference which you should take into account, is that in C# you can only use a switch ()statement when testing a constant expression like a const or enum. This in contrast to Visual Basic .NET where you can test on almost every type. Beside of that, the C# variant is much less flexible. You are not able to switch on two possible values for one statement. In Visual Basic .NET you can separate these values with a comma. Or you will also not able to switch on a range of values, which you can accomplish easily in VB.NET with for example: Case 1 to 4.

Select Case value1
    Case 1 To 4
        ' ...
    Case 5, 6
        ' ...
    Case Else
        ' ...
End Select

const int const1 = 1;
    
switch (const1)
{
    case 1:
        // ...
        break;
    case 2:
        // ...
        break;
    default:
        throw new ArgumentException("Invalid constant", "const1");
}

A last thing I want to mention is that when in Visual Basic .NET a Case statement is evaluated as True, by default the other statements (below) are ignored. In C# you must specify this explicitly by the break keyword. Happy coding! 🙂

Leave a Reply