Mech_Engineer Mech_Engineer - 2 years ago 332 Question class read-only property as list(of T)

I am looking for an example of the usage of a

read-only property as list(of T)

Public ReadOnly Property oList As List(Of String)
Return ...
End Get

When I normally use list(of T) I always use the
constructor in front of my variable type
Public Property oList as New list(of T)

But when I do this now I get an error message from Visual Studio.
So how does this work?

I have never used an read-only property before..

Answer Source

Here's a simple example:

Private myList As New List(Of String)

Public ReadOnly Property List As List(Of String)
        Return myList
    End Get
End Property

or, using an automatic initialized readonly property (supported in Visual Studio 2015, i.e. VB14 and above):

Public ReadOnly Property List As List(Of String) = New List(Of String)

Now consumers can add and remove from your list:


but they cannot replace the list as a whole:

myObject.List = someOtherList ' compile error
myObject.List = Nothing       ' compile error

This has has a few advantages:

  • The invariant that List is never Nothing is always ensured.
  • The consumer of your class cannot do counter-intuitive stuff like "connecting" the lists of two objects:

    myObject1.List = myObject2.List   ' Both objects reference the same list now

As a side note, I would recommend to expose an interface (IList) in such a situation instead of the concrete class:

Public ReadOnly Property List As IList(Of String) = New List(Of String)

This gives you all of the features mentioned above. In addition, you can later change the concrete type of your list to, for example, MyFancyListWithAdditionalMethods without breaking the contract, i.e., without having to recompile the consumers of your library.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download