1

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

2
  • 1
    I would review your design here -- having to cast back up to derived classes is a bad design smell -- if you're saving them in the same collection as a base type, I would expect them to be truly polymorphic (Liskov Principle). Commented Jun 30, 2010 at 9:32
  • Dr Herbie: I am open to suggestions, view this thread: stackoverflow.com/questions/3140281/… Commented Jun 30, 2010 at 9:47

4 Answers 4

7

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());
Sign up to request clarification or add additional context in comments.

1 Comment

Jon is quick on the trigger today (as usual)!
4

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].

Comments

3

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();

Comments

2

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
}

2 Comments

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.
True, business logic insists, that if a cell is in a specific loaction, then it should have the right type. See: stackoverflow.com/questions/3140281/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.