Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB.NET: Property with public getter and protected setter

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.

like image 778
jor Avatar asked Jul 10 '13 12:07

jor


People also ask

Can getters and setters be public?

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.

How do I set the ReadOnly property in VB net?

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.

What is property in VB net explain with an example?

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.

What is get and set property in VB net?

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 .


1 Answers

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
like image 123
Heinzi Avatar answered Sep 21 '22 08:09

Heinzi