16
|
C# & VB.NET Conversion Pocket Reference
Imports System.Runtime.InteropServices
Sub MakeDeposit(<Out( )> ByRef num1 As Integer)
End Sub
This code declares the num1 parameter in MakeDeposit as an
out parameter. The C# version is simpler, since the lan-
guage provides a keyword that automatically adds the
attribute. However, placing the attribute in VB accomplishes
the same task. A drawback of the VB style is that the lan-
guage does not enforce the concept automatically. In C#, if
you mark a parameter as
out, the function must set the
parameter to a value before returning to the caller; other-
wise, the compiler generates an error. But in VB, you can
apply the attribute to a
ByRef parameter or to a ByVal param-
eter. The latter is a mistake, but the compiler does not
enforce the rule.
Passing Function Parameters
In C#, if a function contains ref parameters, you must use
the
ref keyword in front of each by reference argument when
you call it. The same is true for out parameters—the
out key-
word must appear before any argument that corresponds to
an out parameter. Also in C#, it is illegal to pass in a literal
value as an argument for a ref or out parameter. (You cannot
pass a number for a
ref int parameter, for example.) Any
variable you pass as a ref argument must be initialized before
making the method call. The following code segment illus-
trates these principles:
static void DoSomething(int x, ref int y,
out int z)
{
z=45;
}
static void Main(string[] args)
{
int y=4; //you must declare a variable
//and initialize it.
int z;
//notice the use of the ref and out
VB
C#
Syntax Differences
|
17
//before each ref and out argument.
DoSomething(5,ref y,out z);
}
In VB, you do not use any keywords in front of the method
arguments, whether they are
ByVal, ByRef,or<Out> ByRef.
The example below shows how to call functions with
ByRef
parameters in VB.NET:
Imports System.Runtime.InteropServices
Module Module1
Sub DoSomething(ByVal x, ByRef y, <Out( )> ByRef z)
z = 45
End Sub
Sub Main( )
Dim y As Integer
Dim z As Integer
'y and z do not have to be
'initialized because VB auto
'initializes variables
DoSomething(5, y, z)
'it is also legal in VB.NET to
'pass literal values for ByRef
DoSomething(5, 10, 20)
End Sub
End Module
Notice that it is not necessary to use ByRef in front of the
ByRef arguments or to initialize argument variables, because
VB auto-initializes local variables. Notice too that VB lets
you send literal values for
ByRef parameters.
Inside the IL
Whenever you make a method call in VB.NET and you use
a literal value for a
ByRef parameter, at the IL level VB
declares a hidden local variable, assigns it the value you are
passing, and passes the address of the variable instead of the
literal value to the function.
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.