Private Read/Write access and Public Readonly access for variable in my class

m_elias

Member
Joined
Jan 3, 2012
Messages
11
Location
Canada
Programming Experience
1-3
Is it possible to set a variable in my custom class for Private Read/Write access and Public Readonly access without creating Properties with Get and Set? In other words, from within my class I want full access and from my form I only want read access. Right now I declare my variable as either Private or Public to control Public read/write access. I tried googling my question a bit but I'm not sure what the correct terms even are.
 
No, you have to write a ReadOnly property, and internally use the private backing field.
 
No, you have to write a ReadOnly property, and internally use the private backing field.

Is this what you mean?

Class employee
' Only code inside class employee can change the value of hireDateValue.
Private hireDateValue As Date
' Any code that can access class employee can read property dateHired.
Public ReadOnly Property dateHired() As Date
Get
Return hireDateValue
End Get
End Property
End Class
 
That is a ReadOnly property as good as they get.
 
You can also have different access modifiers on the property and either the getter or setter, e.g.
Private _data As Object

Public Property Data() As Object
    Get
        Return _data
    End Get
    Private Set(value As Object)
        _data = value
    End Set
End Property
That will appear externally as a read-only property but internally as read/write.
 
without creating Properties with Get and Set?
If you're worried about having to "write all that", first know that properties is the proper way to expose an objects state to the outside, never declare class variables public. Then learn how to make things easier for yourself, much easier.

The first simplification comes from Auto-implemented properties, in VB 2010 you can declare a full get/set property in one line just like a variable, the only addition is the keyword 'property'. Have a look at this: Auto-Implemented Properties

Then check out Code Snippets: How to: Insert IntelliSense Code Snippets
For example the shortcut for a full get/set property is the word "property". Write that word (*) and press Tab and the skeleton with linked names and types is ready, you can Tab through the highlighted names and types and change them. Similar for a readonly property is the keyword "propread". These names is the Keyword seen in the snippets lists.
You should go through the available snippets to see what they provide, it makes writing common code blocks very fast.

(*) Code editor will actually make this even easier, if you just write "prop" and press Tab Autocomplete will expand that to the word "property", press Tab once more to activate the snippet.
 
Back
Top