-1

Could anyone tell me why executing this

Module Module1
    Sub Main()
        Dim currentSourceData As New SourceData
        currentSourceData.datafiles.Add("234")
    End Sub
End Module

Does give me

System.NullReferenceException: 'Object reference not set to an instance of an object.'

When I use automatic implemented prpoerties

Public Class SourceData
    Public Property datafiles() As List(Of String)
End Class

But it does not when I use a property fully written:

Public Class SourceData
    Private _datafiles As New List(Of String)
    Public Property datafiles() As List(Of String)
        Get 
           Return _datafiles
        End Get
        Set(value As List(Of String))
            _datafiles = value
        End Set
    End Property
End Class
MatSnow
  • 7,357
  • 3
  • 19
  • 31
ruedi
  • 5,365
  • 15
  • 52
  • 88
  • `As New` is the difference, it ensures the backing variable is not nothing. You'll need a constructor (Sub New) to do it with an auto-implemented property. – Hans Passant Jan 24 '19 at 09:48
  • It's almost always a suspect design to have a settable property of a collection type. Do you really want users of this class to be able to *replace* the existing list with one of their own choosing? – Damien_The_Unbeliever Jan 24 '19 at 09:49
  • Duplicate of [List Property Using Auto-Implemented Getter/Setter Returns 'Object reference not set to an instance of an object'](https://stackoverflow.com/questions/26487891/list-property-using-auto-implemented-getter-setter-returns-object-reference-not), in C#, but it doesn't matter in this case and explains the reason. Also [this link about NullReferenceException](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) here at SO will be of help as well. – Trevor Jan 24 '19 at 14:19

1 Answers1

2

The New Operator is missing here:

Public Class SourceData
    Public Property datafiles() As List(Of String)
End Class
MatSnow
  • 7,357
  • 3
  • 19
  • 31