dotnetN00b
dotnetN00b

Reputation: 5131

Why won't this list of struct allow me to assign values to the field?

Public Structure testStruct
    Dim blah as integer
    Dim foo as string
    Dim bar as double
End Structure

'in another file ....

Public Function blahFooBar() as Boolean
    Dim tStrList as List (Of testStruct) = new List (Of testStruct)

    For i as integer = 0 To 10
        tStrList.Add(new testStruct)
        tStrList.Item(i).blah = 1
        tStrList.Item(i).foo = "Why won't I work?"
        tStrList.Item(i).bar = 100.100

        'last 3 lines give me error below
    Next

    return True
End Function

The error I get is: Expression is a value and therefore cannot be the target of an assignment.

Why?

Upvotes: 2

Views: 2169

Answers (3)

Chris Dunaway
Chris Dunaway

Reputation: 11216

I second the opinion to use a class rather than a struct.

The reason you are having difficulty is that your struct is a value type. When you access the instance of the value type in the list, you get a copy of the value. You are then attempting to change the value of the copy, which results in the error. If you had used a class, then your code would have worked as written.

Upvotes: 2

Benjamin Gale
Benjamin Gale

Reputation: 13177

try the following in your For loop:

Dim tmp As New testStruct()     
tmp.blah = 1
tmp.foo = "Why won't I work?"
tmp.bar = 100.100
tStrList.Add(tmp)

Looking into this I think it has something to do with the way .NET copies the struct when you access it via the List(of t).

More information is available here.

Upvotes: 2

deadlyvices
deadlyvices

Reputation: 883

Try creating the object first as

Dim X = New testStruct 

and setting the properties on THAT as in

testStruct.blah = "fiddlesticks"

BEFORE adding it to the list.

Upvotes: 1

Related Questions