Problems with accessing variables

Bozzy

Active member
Joined
Aug 31, 2007
Messages
27
Programming Experience
Beginner
Hi,

I have come across problems when trying to access variables contained in structures in a class.

I have made properties to link to these structures and the variables inside the structures show up fine with the properties, but when I try to use them I get the following error:

Expression is a value and therefore cannot be the target of an assignment.


Any ideas why I would be getting this?


Cheers,
Bozzy
 
Because structures are value types, your properties return a copy of the original value. If you access one of your properties and then directly access a property of the value then you're accessing a property of a copy that is immediately discarded. That will not, and cannot, affect the original value so the compiler will not allow it. You need to assign that copy to a local variable, set the property of the copy via that local variable, then assign the copy back to the property to overwrite the original value with the changes.

Take the Form.Size property as an example. Size is a structure, therefore a value type. You cannot do this:
VB.NET:
myForm.Size.Width = 100
because the copy returned by the Size property is immediately discarded and the original value stored within the form is never changed. The compiler won't let you do something that cannot possibly be of use. What you would need to do would be this:
VB.NET:
Dim size As Size = myForm.Size

size.Width = 100
myForm.Size = size
Now, there is another option open to you, but you need to code for it in your classes. Again using the Form.Size property as an example, you can add an extra property that will allow you to set a sub-property directly. The Form.Size property is implemented something like this:
VB.NET:
Private _size As Size

Public Property Size() As Size
    Get
        Return Me._size
    End Get
    Set(ByVal value As Size)
        Me._size = value
    End Set
End Property

Public Property Height() As Integer
    Get
        Return Me._size.Height
    End Get
    Set(ByVal value As Integer)
        Me._size.Height = value
    End Set
End Property

Public Property Width() As Integer
    Get
        Return Me._size.Width
    End Get
    Set(ByVal value As Integer)
        Me._size.Width = value
    End Set
End Property
So there are two extra properties that allow you to set the Height and Width directly because they don't go via a copy of the original value. It would only be worth doing that if those sub-properties would be set very often, as the Height and Width properties of a form are.
 
Back
Top