In VB.NET is there a way to define a different scope for the getter and the setter of a property?
Something like (this code doesn't work of course):
Public Class MyClass
Private mMyVar As String
Public ReadOnly Property MyVar As String
Get
Return mMyVar
End Get
End Property
Protected WriteOnly Property MyVar As String
Set(value As String)
mMyVar = value
End Set
End Property
End Class
I know that I could just accomplish this with a method that takes the property values as a parameter and sets the private variable. But I'm just curious whether there is a more elegant way that keeps closer to the concept of properties.
In general, they should be public. If they are private they can only be called from within your class and, since you already have access to the private variables within your class, are redundant. The point of them is to allow access to these variables to other, outside, objects.
Assigning a Value. Code consuming a ReadOnly property cannot set its value. But code that has access to the underlying storage can assign or change the value at any time. You can assign a value to a ReadOnly variable only in its declaration or in the constructor of a class or structure in which it is defined.
A property is a value or characteristic held by a Visual Basic object, such as Caption or Fore Color. Properties can be set at design time by using the Properties window or at run time by using statements in the program code. Object. Property = Value.
In this articleThe Get procedure retrieves the property's value, and the Set procedure stores a value. If you want the property to have read/write access, you must define both procedures. For a read-only property, you define only Get , and for a write-only property, you define only Set .
Sure, the syntax is as follows:
Public Property MyVar As String
Get
Return mMyVar
End Get
Protected Set(value As String)
mMyVar = value
End Set
End Property
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With