Syntax Differences
|
35
Short-Circuiting
In addition to syntax differences, if statements in both lan-
guages differ in semantics. The main difference is the use of
short-circuiting in C# by default. Consider the following
example:
static bool DoTask1( )
{
return true;
}
static bool DoTask2( )
{
return false;
}
static void Main(string[] args)
{
//it is unnecessary to execute
//DoTask2 because DoTask1 returns
//True, which is enough to satisfy
//the or clause
if (DoTask1() || DoTask2( ))
{
}
//it is unnecessary to execute
//DoTask1 because DoTask2 returns
//False, which means the clause is
//False
if (DoTask2() && DoTask1( ))
{
}
}
In this example, the function DoTask1 always returns true,
and the function DoTask2 always returns false. C# uses a
technique called short-circuiting, which means that if part of
the statement makes the entire statement true or false, there
is no need to process the rest of the statement. For example,
in an
or operation, if at least one of the clauses is true, then
the entire statement is true. In the example above, DoTask1
returns true; therefore, there is no need to execute DoTask2.
C#
36
|
C# & VB.NET Conversion Pocket Reference
The second half of the code example contains an and opera-
tion. In an
and operation, all clauses have to be true. If one of
the clauses is false, there is no need to evaluate the rest of the
statement. In this example, DoTask2 returns false; therefore,
there is no need to evaluate DoTask1.
VB does not short-circuit by default. In VB, all parts of the
conditional statement are executed unless you use the spe-
cial keywords
AndAlso or OrElse. For example:
Shared Function DoTask1( ) As Boolean
Return True
End Function
Shared Function DoTask2( ) As Boolean
Return False
End Function
Shared Sub Main( )
'VB evaluates each portion of the
'if clause without short-circuiting
If DoTask1() Or DoTask2( )
End If
If DoTask2() And DoTask1( )
End If
End Sub
Both the Or clause and the And clause will execute DoTask1
and DoTask2 without short-circuiting. If you would like to
short-circuit, you must replace
And with the AndAlso key-
word and
Or with the OrElse keyword, as follows:
Shared Function DoTask1( ) As Boolean
Return True
End Function
Shared Function DoTask2( ) As Boolean
Return False
End Function
Shared Sub Main( )
If DoTask1() OrElse DoTask2( )
End If
VB
VB

Get C# & VB.NET Conversion Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.