mjk6026
mjk6026

Reputation: 1484

how can i modify a value in list<t>?

    class SomeClass
    {

        private struct PhraseInfo
        {
            public int Start;
            public int Length;
        }

...

        private void SomeMethod(...)
        {
            List<PhraseInfo> posesBracket = new List<PhraseInfo>();
            posesBracket.Add(new PhraseInfo());
            posesBracket[0].Start = 10;
        }

of cause, posesBracket[0].start=10; occur compiler error CS1612 : "Cannot modify the return value of 'expression' because it is not a variable"

how can i modify a value in list?

Upvotes: 3

Views: 4213

Answers (3)

Louis Kottmann
Louis Kottmann

Reputation: 16618

You cannot have a struct defined as a method. And as they say, you need the reference to change values. So it goes like this:

class SomeClass
    {

        private struct PhraseInfo
        {
            public int Start;
            public int Length;
        }

        private void somemethod()
        {
            List<PhraseInfo> posesBracket = new List<PhraseInfo>();
            posesBracket.Add(new PhraseInfo());
            PhraseInfo pi = posesBracket[0];
            pi.Start = 10;
            posesBracket[0] = pi;
        }
    }

Upvotes: 1

Sergey Metlov
Sergey Metlov

Reputation: 26291

var temp = posesBracket[0];
temp.Start = 10;
posesBracket[0] = temp;

Upvotes: 1

Dr. Snoopy
Dr. Snoopy

Reputation: 56347

The problem is that PhraseInfo is a value type, so the this[] method will return a value, not a reference, to solve it, do this:

PhraseInfo pi = posesBracket[0];
pi.Start = 10;
posesBracket[0] = pi;

Upvotes: 9

Related Questions