Chad Harrison
Chad Harrison

Reputation: 2858

How do you assign values to structure elements in a List in VB.NET?

I have a user-defined structure in a list that I am trying to change the value for in an individual element within the list of structures. Accessing the element is not a problem. However, when I try to update the value, the compiler complains:

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

For example:

Public Structure Person

    Dim first as String
    Dim last as String
    Dim age as Integer

End Structure

_

Public Sub ListTest()

    Dim newPerson as Person

    Dim records as List (Of Person)
    records = new List (Of Person)

    person.first = "Yogi"
    person.last = "bear"
    person.age = 35

    records.Add(person)
    records(0).first = "Papa"  ' <<== Causes the error
End Sub

Upvotes: 22

Views: 37490

Answers (3)

Giorgio Acquati
Giorgio Acquati

Reputation: 121

I had the same problem, and I fixed it by adding a simple Sub to the structure that changes the value of the property.

Public Structure Person

 Dim first as String
 Dim last as String
 Dim age as Integer

 Public Sub ChangeFirst(value as String)
  me.first = value
 End Sub

End Structure

Upvotes: 2

Dan Tao
Dan Tao

Reputation: 128327

There are actually two important concepts to remember here.

One is that, as Hans and Chris have pointed out, Structure Person declares a value type of which copies are passed between method calls.

You can still access (i.e., get and set) the members of a value type, though. After all, this works:

Dim people(0) As Person
people(0).first = "Yogi"
people(0).last = "Bear"
people(0).age = 35

So the other important point to realize is that records(0) accesses the List(Of Person) class's special Item property, which is a sugary wrapper around two method calls (a getter and setter). It is not a direct array access; if it were (i.e., if records were an array), your original code would actually have worked.

Upvotes: 4

Chris Dunaway
Chris Dunaway

Reputation: 11216

As the other comments said, when you refer to records(0), you get a copy of the struct since it is a value type. What you can do (if you can't change it to a Class) is something like this:

Dim p As Person = records(0)
p.first = "Papa"
records(0) = p

Although, I think it's just easier to use a Class.

Upvotes: 15

Related Questions