Link to home
Start Free TrialLog in
Avatar of David_Reid_1985
David_Reid_1985

asked on

VB.NET Implementing Me.Parent property on class.

From a user control we can use the me.Parent property to access the properties and methods of the form which holds the user control.

Can anyone give an example of how this could be done on our own classes? I know we could just have a Parent property of the object and pass a reference of the parent into the constructor, however this would create a copy of the parent object into a private variable within the child. Is there a way to only hold a reference to the parent, then when using any of its functions etc use the actual parent object?
ASKER CERTIFIED SOLUTION
Avatar of ZeonFlash
ZeonFlash

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of VoteyDisciple
VoteyDisciple

It actually wouldn't even have to be ByRef.  .NET, like Java, ALWAYS treats objects as references unless you explicitly make a copy (through some form of .Clone() method that'd have to be class-specific)

ByVal vs. ByRef deals, much more annoyingly, with the pointer variables themselves, not the objects to which they point.  So, ByRef is relevant only if you intend to write a line like the following:

Public Sub New(ByRef MyParent As ParentClass)
    MyParent = New ParentClass() ' Replacing what you were given
End Sub

If you're instead doing the more common...
Public Sub New(ByRef MyParent As ParentClass)
    Me.Parent = MyParent
    Me.Parent.CallSomeMethodThatChangesState()
    Me.Parent.Variable = 3
    ' et cetera
End Sub

... then it can go either way.


The moral is: no matter what you do, passing an object into a function does not implicitly copy the object.  Only C++ does that, and that gave everybody a headache anyway.  (-:
Avatar of Fernando Soto
Hi David_Reid_1985;

When you pass a Object such as a class it alway gets passed as the address of the object and not a copy of the Object.

    Dim obj As MyParent

    Public Sub New( ByVal par As MyClass)
        obj = par
    End Sub

In the above code the class that is creating this class is passing its address to it and that reference is being stored in the variable obj. Obj has access to the original class and a copy was NOT passed in.

Fernando
Hi David_Reid_1985;

To carry on what VoteyDisciple has stated it is safer to always pass ByVal then it is to pass ByRef unless you intend to change the object being passed in, in both the called method and calling method which will destroy the original unless some other variable has a reference to it.

Fernando
Avatar of David_Reid_1985

ASKER

Oh!

Should have really tried it out before assuming it would not work.

Thanks for your help!