tags:

views:

66

answers:

4

A simple question...

I have an abstract class Cell and two classes BorderCell and BoardCell, which inherit from the Cell class. Then I have a Cells array with the type of Cell[], which contains objects of the type BorderCell and BoardCell.

abstract class Cell 
{
}
class BorderCell : Cell 
{
    public void Method1(){};
}
class BoardCell: Cell
{
    public void Method2(){};
}

...

Cell[] Cells = new Cell[x];
for (int i = 0; i < x; i++){
    Cells[i] = new BorderCell();
    // or
    Cells[i] = new BoardCell();
}

Now I want to cast a cell to BorderCell and run its Method1, like this:

(Border)Cells[i].Method1();

But this doesn't work, I have to use:

BorderCell borderCell = (BorderCell)Cells[i];
borderCell.Method1();

Is this the only (and the right way) to do this)?

+7  A: 

No, you just need brackets to make it clear what you want the cast to apply to:

((Border)Cells[i]).Method1();

Basically the "." binds tighter than the cast, so your original code:

(Border)Cells[i].Method1();

is equivalent to:

(Border)  (Cells[i].Method1());
Jon Skeet
Jon is quick on the trigger today (as usual)!
Noldorin
I knew that I was missing something obvious...
_simon_
+4  A: 

Try:

((BorderCell)Cells[i]).Method1();

The brackets provide type boundaries if you use them with casting. Your first attempt didn't wrap the Cell[i].

Adam
+3  A: 

When you write

(BorderCell)Cells[i].method1();

the cast is applied to the expression Cells[i].method1();, which obviously won't work since Cells[i] still returns a Cell.

If you want to spare an additional variable, then write:

((BorderCell)Cells[i]).method1();
Christian
+2  A: 

Since you put cells of 2 types (BorderCell and BoardCell) in the array. I would recommend check the type first before casting.

if (Cells[i] is BorderCell)
{
// cast to BorderCell
}
else
{
// cast to BoardCell
}
Arseny
That depends. If the code knows where there should be BorderCells, so is confident that if it's the wrong type, that indicates a bug, then a cast is the right way to do it.
Jon Skeet
True, business logic insists, that if a cell is in a specific loaction, then it should have the right type. See: http://stackoverflow.com/questions/3140281/what-data-structure-to-use-in-my-example
_simon_