Results 1 to 3 of 3

Thread: Using ReadOnly properly

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Dec 2007
    Posts
    70

    Using ReadOnly properly

    I have a public readonly variable in a module, but when I try to set it in my form load event for the first time I get 'ReadOnly' variable cannot be the target of an assignment.

    It is my understanding that a ReadOnly variable can only be set once and after that you would get an error when setting it.

  2. #2
    PowerPoster
    Join Date
    Apr 2007
    Location
    The Netherlands
    Posts
    5,070

    Re: Using ReadOnly properly

    I think you can only initialize ReadOnly fields when declaring them, or in the constructor:
    Code:
    Public ReadOnly Name As String = "ABC"
    or
    Code:
    Public Readonly Name As String
    
    Public Sub New()
       Name = "ABC"
    End Sub
    Since you are talking about a module, only the first is an option.

    If you do need to set the value at a later stage, consider a ReadOnly property instead. You can still make the private backing field writable:
    Code:
    Private _Name As String
    Public ReadOnly Property Name() As String
       Get
          Return _Name
       End Get
    End Property
    Now you can set the backing field to change the value of the property from within the same class (obviously not outside of the class).
    In the same class, you can read and write:
    Code:
    'Read
    MsgBox(Me.Name)
    
    'Write
    _Name = "DEF"
    From the outside, any other class, you can only read:
    Code:
    'Read
    MsgBox(classInstance.Name)
    
    'Write
    classInstance.Name = "DEF"  ' readonly error (Name is readonly)
    classInstance._Name = "DEF"  ' access modifier error (_Name is private)

  3. #3
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Using ReadOnly properly

    Quote Originally Posted by Disyne View Post
    It is my understanding that a ReadOnly variable can only be set once and after that you would get an error when setting it.
    This is another case when you simply need to consult the documentation.
    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.
    http://msdn.microsoft.com/en-us/library/z2b2c2ka.aspx
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width