Home > Net >  How to use some property of parent class in child class Vb.net?
How to use some property of parent class in child class Vb.net?

Time:10-17

Lets say I have a class named as "Class Section" having two properties i.e. area and mElement. Like this:

    Public Class ClassSection

    Public Property area as double 
    Public Property mElement as ClassElement

    End Class

Now i want to use ClassSection (parent class) property "area" in mElement. Like this in below code.

    Public Class ClassElement

    Public Sub CalculateAreaRatio()
    Dim AreaRatio as Double
    AreaRatio=Area/10 'This area is ClassSection Area
    End Sub
    
    End Class

How this can be done. Thank you in advance

CodePudding user response:

As I have said in my comment every ClassElement that you create is unaware if it is contained in a ClassSection element or not. If you want to let know each element of this relationship you should pass the container to the ClassElement instance.

So let's change the ClassElement structure to this one

Public Class ClassElement

    Dim myParent As ClassSection
    
    Public Sub New(parent As ClassSection )
        myParent = parent
    End Sub
    
    Public Function CalculateAreaRatio() As Double
        Dim AreaRatio As Double
        AreaRatio = MyParent.Area / 10 'This area is ClassSection Area
        Return AreaRatio
    End Function 
End Class

Now every time you create a ClassElement you are forced to pass into the constructor code the ClassSection container. And you save the instance passed in a private field. This private field can be used inside the CalculateAreaRatio.

The calling code could be something like this one

Dim section As ClassSection = New ClassSection With {
        .area = 3
}
section.mElement = New ClassElement(section)
Console.WriteLine(section.mElement.CalculateAreaRatio())
  • Related