whytheq whytheq - 1 year ago 60
Vb.net Question

Why can't I have auto-implemented Read-only properties

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
Return fText
End Get
End Property

Answer Source

There would be no way to set the value of Text

If a property has a setter and a getter you can use the setter to set the value

obj.Text = "some value"

However if you remove the setter (make it readonly) the above line no longer compiles. So how would you set the value? If you are unable to set the value of a property the idea of that property vanishes.

The simple way around that is to have the compiler enforce you to define how to get the value of the property. In your example you are using a backing field which can be assigned. Problem solved. It could also be a calculated property value. The point is you need some mechanism to provide the value for a readonly property.

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