Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a value inside parent class from child class (in nested classes)?

I have Class1 and class2 which is inside class1, VB.NET code:

Public Class class1
    Public varisbleX As Integer = 1
    Public Class class2
        Public Sub New()
            'Here GET the value of VariableX
        End Sub
    End Class

    Public Sub New()
        Dim cls2 As New class2
    End Sub
End Class

I want to access varisbleX from class2, code in VB.net or C# is appreciated, Thanks.

like image 987
Towhid Avatar asked Jan 01 '12 09:01

Towhid


People also ask

Can you pass values from child class to parent class in Java?

The parent class can hold reference to both the parent and child objects. If a parent class variable holds reference of the child class, and the value is present in both the classes, in general, the reference belongs to the parent class variable. This is due to the run-time polymorphism characteristic in Java.

How do you access the variables of parent class in a child class in Python?

Accessing Parent Class Functions This is really simple, you just have to call the constructor of parent class inside the constructor of child class and then the object of a child class can access the methods and attributes of the parent class.

Can we assign child class object to the parent class variable?

We can assign child class object to parent class reference variable but we can't assign parent class object to child class reference variable.


1 Answers

The inner class (class2) is not associated with any specific instance of the outer class (class1). T access fields etc, you will need to first have an explicit reference to a class1 instance, probably passing it in via the constructor. For example, it could be:

Public Class class1
    Public varisbleX As Integer = 1
    Public Class class2
        Public Property Parent As class1

        Public Sub New(oParent As class1)
            Me.Parent = oParent
            Console.WriteLine(oParent.varisbleX)
        End Sub
    End Class

    Public Sub New()
        Dim cls2 As New class2(Me)
    End Sub
End Class
like image 114
Marc Gravell Avatar answered Nov 15 '22 09:11

Marc Gravell