I have the following
Public Structure Foo
dim i as integer
End Structure
Public Class Bar
Public Property MyFoo as Foo
Get
return Foo
End Get
Set(ByVal value as Foo)
foo = value
End Set
dim foo as Foo
End Class
Public Class Other
Public Sub SomeFunc()
dim B as New Bar()
B.MyFoo = new Foo()
B.MyFoo.i = 14 'Expression is a value and therefore cannot be the target of an assignment ???
End Sub
End Class
My question is, why can I not assign to i through my property in the Bar class? What have I done wrong?
The answer is found here, it says the following:
' Assume this code runs inside Form1.
Dim exitButton As New System.Windows.Forms.Button()
exitButton.Text = "Exit this form"
exitButton.Location.X = 140
' The preceding line is an ERROR because of no storage for Location.
The last statement of the preceding example fails because it creates only a temporary allocation for the Point structure returned by the Location property. A structure is a value type, and the temporary structure is not retained after the statement runs. The problem is resolved by declaring and using a variable for Location, which creates a more permanent allocation for the Point structure. The following example shows code that can replace the last statement of the preceding example.
This is because the struct is only a temporary variable. So the solution is to create a new struct of the type you need, assign it all it's internal variables and then assign that struct to the struct property of the class.
You could do
Dim b as New Bar()
Dim newFoo As New Foo()
newFoo.i = 14
b.MyFoo = newFoo
To work around the problem.
Trying the same in C# with the code
class Program
{
public void Main()
{
Bar bar = new Bar();
bar.foo = new Foo();
bar.foo.i = 14;
//You get, Cannot modify the return value of ...bar.foo
// because it is not a variable
}
}
struct Foo
{
public int i { get; set; }
}
class Bar
{
public Foo foo { get; set; }
}
Which I think, is a more direct way of saying the same thing as
Expression is a value and therefore cannot be the target of an assignment
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With