4

This is allowed:

Public Property Text() As String

Whereas for a read-only property why aren't I allowed an equivalent?

Public ReadOnly Property Text() As String

I seem to be forced to use:

Public ReadOnly Property Text() As String
    Get
        Return fText
    End Get
End Property
Rune FS
  • 21,497
  • 7
  • 62
  • 96
whytheq
  • 34,466
  • 65
  • 172
  • 267
  • 2
    For comparison, in C# you could have `public string Text { get; private set;}`, which would be readonly to other types, and read-write from within the current type. – Marc Gravell Jan 11 '13 at 08:13
  • @MarcGravell technically that's not a read only property it's a property with a private setter. contrast that with Eg. a property just a getter and a readonly backing field. Seen from eg. the point of view of an optimizer those are different – Rune FS Jan 11 '13 at 08:18
  • 1
    @RuneFS oh, I'm well-aware of that; but my statement stands: to other types it *operates* as read-only (there is no public setter). – Marc Gravell Jan 11 '13 at 08:19
  • @MarcGravell I never doubted that you were aware :) however I do think your comment is somewhat misleading. another type can set the value of either so in that respect they are the same however seen from a code generation/optimization they are _not_ the same. One is accessing a a read-write property the other is not. The fact that only certain code can change the value doesn't change the fact that it could have been since the last read – Rune FS Jan 11 '13 at 09:04
  • @RuneFS read-only is an overloaded concept. If I had meant `readonly` *keyword* as in *fields*, I would have stylized the `readonly`. And technically, even `readonly` is not a *hard guarantee* that the value hasn't changed (all things are possible if you try). – Marc Gravell Jan 11 '13 at 09:17
  • @MarcGravell oh yes even this can be null (http://stackoverflow.com/a/6864042/112407) – Rune FS Jan 11 '13 at 12:08

1 Answers1

5

It is now supported in VB14 (Visual Studio 2015 and later). Auto-implemented properties can be initialized with initialization expressions:

Public ReadOnly Property Text1 As String = "SomeText"
Public ReadOnly Property Text2 As String = InitializeMyText()

or in the constructor:

Public ReadOnly Property Text As String

Public Sub New(text As String)
    Me.Text = text
End Sub

Details:

Heinzi
  • 167,459
  • 57
  • 363
  • 519