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.
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.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.