Constructors

David_nyh

Member
Joined
Mar 4, 2005
Messages
16
Programming Experience
Beginner
How do you call a constructor from your nested class? See bold text:

VB.NET:
 Public Class A
    Public Class B
        Private m_Age As Integer
 
        Property Age() As Integer
            Get
                Return m_Age
            End Get
            Set(ByVal Value As Integer)
                If Value < 0 Then
                    Throw New Exception("Leeftijd fout ingegeven.")
                End If
                m_Age = Value
            End Set
        End Property
 
        Public Sub New(ByVal age As Integer)
            Me.Age = age
        End Sub
 
        Overrides Function ToString() As String
            Return "Age: " & Age.ToString()
        End Function
    End Class
 
    Private m_AgeB As B
    Private m_Name As String
 
    Property AgeB() As B
        Get
            Return m_AgeB
        End Get
        Set(ByVal Value As B)
            m_AgeB = Value
        End Set
    End Property
 
    Property Name() As String
        Get
            Return m_Name
        End Get
        Set(ByVal Value As String)
            Value = m_Name
        End Set
    End Property
 
    Public Sub New(ByVal name As String)
        Me.Name = name
    End Sub
 
    Public Sub testscherm()
        Console.WriteLine("Name: " & Name)
        Console.WriteLine(AgeB)
    End Sub
End Class
 
Module HeadProg
    Sub Main()
        Try
            [B]Dim test As New A("David", 18)[/B]
            test.testscherm()
            Console.WriteLine()
        Catch ex As Exception
            Console.WriteLine("Fault : " & ex.Message)
        End Try
    End Sub
End Module

Thanks

David
 
you need to include a New sub to take the parameters when declaring the class:
VB.NET:
Sub New(ByVal Name As String, ByVal Age As Integer)
    MyBase.new()
    Me.Name = Name
    Me.Age = Age
End Sub
 
I have to change this code in class A (not the nested class):
VB.NET:
Public Sub New(ByVal name As String)
        Me.Name = name
End Sub

To your example?

If I do this I get a objectreference fault
 
i'm sorry i didnt see that you had a New sub already

what's the purpose for storing the age in it's own class?

each person only has 1 age therefor you can store their age in the same class as their name
 
If you want New A(x, y) you must change the A constructor or overload it with a method that also allow two parameters.

You access the base class (B) instance with the MyBase keyword.

If base class don't have a constructor that allow no parameters you must call the MyBase.New(params) in A constructor methods. This is also what the IDE error message says if you try to do so.
 
Back
Top