0

Why does the Compiler complain about the following line

Public ReadOnly Property Name As String

that

error BC30126: 'ReadOnly' property must provide a 'Get'

I thought auto-implemented readonly properties were supported in VB 14? Or am I doing something wrong here by compiling from the Commandline using vbc.exe delivered by the .NET Framework 4.0.30319 with Microsoft (R) Visual Basic Compiler version 14.6.1586?

Do I need to use Visual Studio to support that?

Edit: A concrete Example - shouldn't this work?

Class A
    Sub New(name As String)
        Me.Name = name
    End Sub
    Public ReadOnly Property Name As String
End Class

The above example indeed should work but doesn't in my case. Can someone for whom this is working please confirm that his Compilerversion is any different than mine?

Ňɏssa Pøngjǣrdenlarp
  • 38,411
  • 12
  • 59
  • 178
Tobi Holy
  • 85
  • 6
  • 2
    The answer to the proposed duplicate clearly states that the code in this question should work with VS 2015 (you can have a ReadOnly auto-property and initialise in in the constructor). So the answer to this question is not contained in the proposed dupe. – Blackwood Feb 27 '17 at 17:28

1 Answers1

1

AutoProperties must be initialised.

You have to do something like this:

Public ReadOnly Property Name As String = "Something"

Or dropping the AutoProperty:

Public ReadOnly Property Name As String
    Get
        Return "FixedName"
    End Get
End Property

Or

Private m_Name as String = ""
Public ReadOnly Property Name As String
    Get
        Return m_Name
    End Get
End Property
A Friend
  • 2,750
  • 2
  • 14
  • 23
  • Can't I initialize the property in the constructor? – Tobi Holy Feb 27 '17 at 16:34
  • After trying the code I just wrote I don't actually get a compilation error without the initialisation, but the property returns Nothing. Your compiler just might not like it, or my VS settings are too lax. – A Friend Feb 27 '17 at 16:42
  • The normal usage of read-only autoprops is to initialize the property in the constructor - and that's fine, so long as you're using an appropriate version of VB. – Jon Skeet Feb 27 '17 at 16:49
  • @JonSkeet can you elaborate on the appropriate version of VB? What version is appropriate? Sorry, but I'm getting bitten by this all over. – Pedro Rodrigues Aug 05 '20 at 09:47
  • 1
    @PedroRodrigues: VB14, I believe. – Jon Skeet Aug 05 '20 at 10:04