Constant and ReadOnly Fields          
                                             
A class can define fields that are constant. Simply apply the
Const modifier to a field to make it constant. You
must initialize a constant field to another constant value, either a literal or a constant variable. Of course, once
initialized, constant values will never change.


Public Class MyConstants
   'Initializing constants, these are valid
   Public Const c1 As Integer = 1
   Public Const c2 As String = "Another Constant"
   Public Const c3 As String = c2
 
   '**** These are INVALID! *****
   Public Const c4 As EmployeeBenefits = New EmployeeBenefits()
   Public Const c5() As Integer = {1, 2, 3, 4}
   Public Const c6 As String = mName
End Class


Viewing the resulting assembly in ildams.exe reveals that the VB  compiler handles constants by "hard coding"
the value into the CIL. Also note that Const members are implicitly Shared, seen within ildasm via the
‘static’
modifier.

























Use the ReadOnly modifier to define a variable that needs to be initialized with a non-constant value, but should
never change after initialization. The important distinction between ReadOnly fields and Const fields is when
they are resolved. The value of a constant field is hard coded into the CIL at compile time. The value of a read
only field is determined dynamically at runtime. Also, ReadOnly fields are instance fields, whereas Const fields
are implicitly shared.


Class MyConstants

   Private Shared mName as String = "Homer"

   '**** These are INVALID! *****
   Public Const c4 As EmployeeBenefits = New EmployeeBenefits()
   Public Const c5() As Integer = {1, 2, 3, 4}
   Public Const c6 As String = mName

   'All of the above work if you use ReadOnly instead of Const
   Public ReadOnly r1 As EmployeeBenefits = New EmployeeBenefits()
   Public ReadOnly r2() As Integer = {1, 2, 3, 4}
   Public ReadOnly r3 As String = mName
   Public ReadOnly r4 As String

   Public Sub New()
      'You can initialize readonly fields in a ctor, but
      'not in any other method.
      r4 = "Assigning a read-only value"
   End Sub  
End Class
Copyright (c) 2008.  Intertech, Inc. All Rights Reserved.  This information is to be used exclusively as an
online learning aid.  Any attempts to copy, reproduce, or use for training is strictly prohibited.
Constant and ReadOnly Fields
Table of Contents
Courseware
Training Resources
Tutorials
Services