In Visual Basic, a property can be declared in two ways:
' Auto-implemented property Public Property Name As String ' Full property Private _age As Integer Public Property Age As Integer Get Return _age End Get Set(value As Integer) If value < 0 Then Throw New ArgumentException("Age can't be negative") _age = value End Set End Property
Nuances when using Set:
Value keyword is a pseudo-variable that refers to the assigned value.Set, you can perform validation, logging, or trigger events.When to use:
What are the consequences of writing
Set(ByVal value As Integer)instead ofSet(value As Integer)in VB.NET? Why is it not advisable to do this?
Answer:
VB.NET syntax does not require (and does not support) declaring the ByVal parameter explicitly in Set — simply use Set(value As Type). If you write Set(ByVal value As Integer), it will result in a compilation error.
Example of erroneous code:
'Set(ByVal value As Integer) — compilation error Public Property Prop As Integer Set(ByVal value As Integer) ... End Set End Property
In classic VB6, such syntax was permissible, but in VB.NET it strictly requires Set(value As Type).
History
ByVal was incorrectly placed in Set — the compiler issued cryptic errors that were difficult to localize because the linter did not show a clear cause.History
History
While copying reference-type objects through auto-implemented properties, deep copy was forgotten to be implemented through Get/Set. As a result, duplications of references to the same object were obtained; changing one instance led to changes in another.