views:

169

answers:

4

I got the following error which I translated from german:

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

Iam 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?

+1  A: 

What's the problem in making it a class?

Also, why don't you just use an indexer instead:

public object this[int column, int row] {
    get { return this.GetCellValue(column, row); }
    set { this.SetCellValue(column, row, value); }
}

that way, you can use it like that:

sheet[column, row] = newValue;
Botz3000
I forgot to say I cannot modify the VB code, just the C# code. As I said, the problem making it a class is that it wastes memory huge time..
codymanix
A: 

If it is a struct, you're going to have to get the value out, modify it, and pass it back in:

Cell cell = sheet.Cells(row, col);
cell.Value = newVal;
sheet.Cells(row, col) = cell; // assuming this has a setter

But frankly I think your assertion of an object (class) per cell being too expensive is missing the point...

BTW, I would also advise that structs should be immutable whenever possible (with the possible exception of XNA, for specific reasons).

Marc Gravell
In fact, my struct *is* immutable. Note that the only setter in Cell is just calling ws.GetCellValue(x, y) so it doesnt modify itself. It is just the VB.NET compiler which *thinks* that my struct is mutable, which is wrong, and that is my whole problem :)
codymanix
A: 

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.

codymanix
A: 

My answer would have been - don't make the Value a property. Make it two methods - GetValue() and SetValue(). This way there are no assignments.

Vilx-