1

I am currently converting a project from VB to C#. I have a Web Reference in the VB project which I have referenced in the C# project (Add Web Reference). The signatures are the same. The VB code looks like this:

If Not tws.StartSession(tsd) Then
    Throw New systemMonitor.internalEx.securityEx("Failed to initiate a TROPOS session")
End If

I have tried to covert that across as this:

// Start our session
if (!this._service.StartSession(this._details))
    throw new Exception("The TROPOS session failed to start.");

The problem I have, is that it won't compile and comes up with the error:

argument 1 must be passed with the 'ref' keyword

so I changed it to this:

// Start our session
if (!this._service.StartSession(ref this._details))
    throw new Exception("The TROPOS session failed to start.");

which compiles and runs (although nothing seems to happen, but that is another issue). My question is simple. In VB do you not have to set the ByRef keyword?

r3plica
  • 13,017
  • 23
  • 128
  • 290

2 Answers2

1

In VB.NET ByRef or ByVal is (optionally) specified in the method being called (with the default being ByVal if neither is specified) and you don't specify it when calling the method.

In C# if the method specifies ref for the parameter then you must also specify 'ref' when calling the method.

Matt Wilko
  • 26,994
  • 10
  • 93
  • 143
Scott Hannen
  • 27,588
  • 3
  • 45
  • 62
-2

You do not need to specify ByRef in VB.NET

The short answer is no, you don't have to.

Here's why: Once again VB.NET does things for you, if it is an object that is passed to a function, it will automatically be passed by reference. So under the covers VB.NET adds it for you. VB.NET will pass simple data types (Strings, Integers, etc...) ByVal automatically unless you specify ByRef.

Personally I like to write my code explicitly using ByRef when I mean to pass something by reference. I also use following compiler options:

Option Explicit On
Option Strict On

Which limits the amount of things VB does automatically for me. I don't think however it has an affect on passign objects by reference.

CowWarrior
  • 3,147
  • 2
  • 15
  • 10
  • 2
    `if it is an object that is passed to a function, it will automatically be passed by reference` That is false. It will, by default, be passed by value. The only thing going on here is that if the method definition defines the parameter as being passed by reference, the caller doesn't *also* need to explicitly state it; it's implied, but the method definition *does* still need to explicitly state it. – Servy Jun 22 '16 at 13:46
  • 1
    Far too many programmers just don't get this - reference types are *not* automatically passed 'byref'. 'ByRef' parameters mean that you can reassign the object to a new or different instance and have the change seen at the call location. If the parameter is 'ByVal', changing the object 'identity' will not have any effect outside of the method. – Dave Doknjas Jun 22 '16 at 13:59