Question

I am writing a function which is passed in a list which is partially filled. I'd like to set some of the fields within the list inside this function. I thought that passing it as a reference would allow me to do this, however, I get the following error:

Error 1 Cannot modify the return value of 'System.Collections.Generic.List.this[int]' because it is not a variable

I am wondering what I might need to do to tell C# that I wish to have the option of modifying the contents of the list.

Here is a summarized version of my code:

    public static void Determine_RTMM_Descriptor(ref List<Struct_Descriptor_Type> symbols, string Dwarf_Output_Filename)
    {
        ...
        lines = System.IO.File.ReadAllLines(Dwarf_Output_Filename);

        //loop on symbol names
        for (int idx = 0; idx < symbols.Count; idx++)
        {

            if(symbols[idx].size == 0) 
                symbols[idx].size = (int)new System.ComponentModel.Int32Converter().ConvertFromString(split_line[DwarfInterface.SIZE_INDEX]);

        ...
    }

Thanks in advance for any help.

Was it helpful?

Solution

The underlying issue here is that you have a list of value types. When you use the indexer of the list to get an item from the list you are getting a copy of that type. The code symbols[idx] is the value of that item. It is not a variable representing that item, as the error message is telling you.

You're trying to mutate the size of the copy, which will have no effect on the item of the list. This is such a common mistake that the compiler even makes this an error.

If you really are sure that you want to have a mutable value type (hint: you aren't, and you shouldn't have one; you almost certainly just want to have a class here to avoid this problem entirely) then you would need to get the value of the item, mutate it, and then set the item again:

if(symbols[idx].size == 0) 
{
    var symbol = symbols[idx];
    symbol.size = 42;
    symbols[idx] = symbol;
}

OTHER TIPS

Your return type on the function is "void" when you should set the return type to the list. That should allow you to change it and return it modified.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top