Search code examples
c#.netstructvalue-type

Cannot assign property of struct returned from method


I got the following error which I translated from German:

error BC30068: The Expression is a value and cannot be target of an assignment.

I am trying to do the following:

sheet.Cells(row, col).Value = newVal ' this is VB

Where I have declared Cells as:

public Cell Cells(int x, int y) // this is C#
{
    return new Cell(this, x, y);
}

public struct Cell
{
    Worksheet ws;
    int x;
    int y;

    public Cell(Worksheet ws, int x, int y)
    {
        this.ws = ws;
        this.x = x;
        this.y = y;
    }

    public object Value
    {
        get { return ws.GetCellValue(x, y); }
        set { ws.SetCellValue(x, y, value); }
    }
}

How can I solve this problem? I do not want Cell to be a Class but instead to be a struct, because otherwise any access would create a new object on the heap. Sure I could cache all created Cell Objects but this could introduce bugs and wastes lots of memory and a new layer of indirection.

Is there a better way to do it?


Solution

  • I now solved it by returning a CellCollection from the Cells property which contains an indexer. This way Iam no more getting the error and I just create one single object for all cells.