I am constructing a collection of objects, and need to use inheritance on a base class – I have been trying for hours in various ways and can’t get this to work whatsoever – the error is always “Object reference not set to an instance of an object.”
The idea in the example below is that an object is instantiated, and within that lies a collection of Students when I try to access the oDemo.Students(0).Name property the error is raised. Otherwise the object appears to have instantiated OK.
Here is the code being used to instantiate and access the class (from ASP.NET).
Dim oDemo As New MyDemo.Students
lblTest.Text = oDemo.Student(0).Name
Here is the sample code from the class library:
Public Class Students
Private p_Students As System.Collections.Generic.List(Of Test)
ReadOnly Property Student() As System.Collections.Generic.List(Of Test)
Get
Dim alTestNames As New ArrayList()
alTestNames.Add("John")
alTestNames.Add("Brian")
alTestNames.Add("Scott")
For iLoop As Integer = 0 To alTestNames.Count - 1
p_Students.Add(New Test(alTestNames(iLoop).ToString))
Next
Return p_Students
End Get
End Property
End Class
Public MustInherit Class TestBase
Private p_Name As String
ReadOnly Property Name() As String
Get
Return p_Name
End Get
End Property
Sub New(ByRef sName As String)
p_Name = sName
End Sub
End Class
Public Class Test
Inherits TestBase
Sub New(ByRef sName As String)
MyBase.New(sName)
End Sub
End Class
I’m not sure if I am totally missing the point in some way – any help is gratefully received. If any more info/background is needed please advise.
You never initialized the p_Students field, it is Nothing and causes the exception. Fix:
Note the New keyword. That’s the quick fix, a more sane approach would be: