Types of Properties

  • There may be times when you would like to have a property that can only be read or that can only be written. That means when you create an Interface to the user you may not want him to change the value of a variable but he can read that value. Or such cases where you want him to change the value but can not see the value of the variable. So you have three types of properties and they are
    1. Readonly properties
    2. Writeonly properties
    3. Default properties
Readonly properties
  • You can make a property read only by using the key word ReadOnly as given below
  • Public ReadOnly Property GetSerialNumber()
    Get
    End Get
    End Property
  • When you press the Enter key after the first line of code, VB.net automatically supplies the skeletal code for the Get statement block. The ReadOnly keyword causes VB.NET to omit the set statement block because it is not needed with a ReadOnly property. So you can not set the value for a variable.
Example
Module Module1
Sub Main()
System.Console.WriteLine("Value from module " & Module2.prop1)
End Sub
End Module
Module Module2
Private PropertyValue As Integer = 6
Public ReadOnly Property prop1() As Integer
Get
Return PropertyValue
End Get
End Property
End Module

Writeonly properties
  • Similarly you can make a property Write only by using the key word WriteOnly as given below
  • Public WriteOnly Property SetHours()
    Set(ByVal Value)
    End Set
    End Property
  • When you press the Enter key after the first line of code, VB.NET automatically supplies the skeletal code for the Set statement block. The WriteOnly keyword causes VB.NET to omit the get statement block because it is not needed with a WriteOnly property. So you can not retrieve the value of a variable.
Example
Module Module1
Sub Main()
Module2.prop1 = 2
End Sub
End Module
Module Module2
Private PropertyValue As Integer
Public WriteOnly Property prop1() As Integer
Set(ByVal value As Integer)
PropertyValue = value
End Set
End Property
End Module

Default properties
  • Declaration includes Default keyword
  • These properties must have parameters
  • These can be set or retrieved without specifying the property name
  • Example Public Class class1
    Private Data(200) As Integer
    Default Public Property Property1(ByVal Index As
    Integer) As Integer
    Get
    Return Data(Index)
    End Get
    Set(ByVal value As Integer)
    Data(Index) = value
    End Set
    End Property
    Public Property
    End Class
    ‘creating the object and invoking the property. Here need ‘not use property name
    Public ob1 as New class1()
    ob1(1) = 55
    MsgBox(ob1(1))


Properties<< Previous

Next>>Inheritance

Our aim is to provide information to the knowledge seekers. 


comments powered by Disqus
Footer1