Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

By Ref parameters in VB.NET and C#

I have question related passing parameters byRef, I have VB.NET based class library in which some functions are defined with byref argument types. These parameters are parent class objects and when I tried to call this function and pass child class object in byref argument it works in VB.NET but I am unable to do same thing in C#

following is test code i am trying

Public Class Father

        Private _Cast As String
        Public Property Cast() As String
            Get
                Return _Cast
            End Get
            Set(ByVal value As String)
                _Cast = value
            End Set
        End Property

    End Class


 Public Class Son
        Inherits Father

        Private _MyName As String
        Public Property Myname() As String
            Get
                Return _MyName
            End Get
            Set(ByVal value As String)
                _MyName = value
            End Set
        End Property


    End Class

Implementation class in VB

Public Class Parent

        Public Function Show(ByRef value As Father) As Boolean
            Dim test As String = value.Cast
            Return True
        End Function

// Herer I can call Show method and pass child object to ByRef type argument and it works

Public Function Show2() As Boolean

            Dim s As New Son
            Dim result As Boolean = Show(s)

            Return True
        End Function

    End Class

// But when i try same thing in c#

Parent p = new Parent();
            Son s = new Son();
            Father f = new Father();

            p.Show(ref s);

I get error that Son cannot convert to father , I already test it works in VB but how can I make it work in c#? as I have class library in dll format

Thanks in advance

like image 408
user2439901 Avatar asked May 31 '13 09:05

user2439901


People also ask

What are ref and out parameters in C#?

ref is used to state that the parameter passed may be modified by the method. in is used to state that the parameter passed cannot be modified by the method. out is used to state that the parameter passed must be modified by the method.

What is ref parameter in C#?

When used in a method's parameter list, the ref keyword indicates that an argument is passed by reference, not by value. The ref keyword makes the formal parameter an alias for the argument, which must be a variable. In other words, any operation on the parameter is made on the argument.

What are ref parameters?

A reference parameter is a reference to a memory location of a variable. When you pass parameters by reference, unlike value parameters, a new storage location is not created for these parameters. The reference parameters represent the same memory location as the actual parameters that are supplied to the method.

Does VB pass by reference?

In Visual Basic, you can pass an argument to a procedure by value or by reference. This is known as the passing mechanism, and it determines whether the procedure can modify the programming element underlying the argument in the calling code.

What is a reference return value in VB NET?

When an method provides a reference return value to a caller, modifications made to the reference return value by the caller are reflected in the called method's data. Visual Basic does not allow you to author methods with reference return values, but it does allow you to consume reference return values.

What is the difference between the ByRef and ByVal parameters?

Because debt is a ByRef parameter, the new total is reflected in the value of the argument in the calling code that corresponds to debt. Parameter rate is a ByVal parameter because Calculate should not change its value. Module Module1 Sub Main () ' Two interest rates are declared, one a constant and one a ' variable.

How do you pass arguments by reference in VB?

Passing Arguments by Value and by Reference (Visual Basic) In Visual Basic, you can pass an argument to a procedure by value or by reference. This is known as the passing mechanism, and it determines whether the procedure can modify the programming element underlying the argument in the calling code.

What does ByRef mean in C++?

ByRef, by reference, means the variable location itself is copied. Example. This program introduces 2 subs other than the Main subroutine. It shows the Example1 method, which receives an integer parameter ByVal, and the Example2 method, which receives an integer ByRef.


2 Answers

C# is strict about this, a variable that's passed by reference must be an exact match with the method argument type. VB.NET is forgiving about that, its compiler rewrites your code and creates a variable of the required type. Roughly like this, expressed in C#:

    Son s = new Son();
    Father $temp = (Father)s;
    p.Show(ref $temp);
    s = (Son)$temp;

Which is nice, but not without problems. The failure mode is when the Show() method assigns a new object to its argument of the wrong type. It is allowed to create a Father object since the argument type is Father. That however will make the 4th statement in the above snippet fail, can't cast Father to Son. That's not so pretty, the exception will be raised at the wrong statement, the true problem is located in the Show() method. You can scratch your head over that for a while, not in the least because the cast is not actually visible in your VB.NET source code. Ouch. C# forces you to write the above snippet explicitly, which solves your problem.

At this point you should exclaim "But wait, the Show() method doesn't actually create a new object!" That's good insight and you'll have found the true problem in this code, the Show() method should not declare the argument ByRef. It should only be used when a method reassigns the argument and that change needs to be propagated back to the caller. Best avoided entirely, an object should be returned by a method by its return value. Function in VB.NET instead of Sub.

like image 128
Hans Passant Avatar answered Oct 23 '22 09:10

Hans Passant


ByRef allows the function to modify the managed pointer and make it point to something other than a Son, therefore C# won't allow you to pass a managed pointer to Son directly. However, you can do this:

Son s = new Son();
Father f = s;
p.Show(ref f);
s = (Son)f; //Success if f still points to a Son, InvalidCastException  otherwise.

However, if your method Show really does not modify the managed pointer, then there is no reason for taking it ByRef: Just pass it ByVal and you'll still be able to modify the object itself.

like image 4
Medinoc Avatar answered Oct 23 '22 09:10

Medinoc