Property Accessibility
June 1st, 2007
Often when we’re designing a class we will notice that one or more properties should be Read-Only to the outside world but Read-Write at a tighter scope. A common way to do this in the past was to simply use the underlying property variable to set the variable internally. This worked but it could get complicated if there was processing logic in the property routine that needed to be called or if you needed to create a subclass. Now, however, in VS 2005 you can set the access level of the Property Get and Set separately.
VB.NET has four levels of accessibility:
- Public - Available in all assemblies
- Friend - Available only to code in the current assembly
- Protected - Available only to subclasses of this class regardless of assembly
- Private - Available only to code in the same class
For example, let’s assume that you’re creating a base class that will probably be subclassed. In this class you have a property that the subclass should be able to set but that should not be available to other code. Here’s how it would look:
Public Property Example() As String Get Return Example End Get Protected Set(ByVal value As String) _example = value End Set End Property
Note that the Set part of the property has Protected prefixing it. This means that non-subclasses can’t set the property but a subclassing class could access it through the MyBase object.
In this example,
Public Property Example() As String Get Return Example End Get Friend Set(ByVal value As String) _example = value End Set End Property
You would want code internal to your namespace to be able to set the value of this property but you only wanted to offer Read-Only access to external code. The Friend accessor is what you would use in this case.
Using the right access level for your properties, both the get and set portions, will increase the readability and stability of your code.
Entry Filed under: VB.NET Tutorials
Rate This Article:











Leave a Comment
Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>
Trackback this post | Subscribe to the comments via RSS Feed