Re: Inheritance Problem



"Jon Skeet [C# MVP]" <skeet@xxxxxxxxx> wrote in message
news:MPG.209f9ef9718717b12c@xxxxxxxxxxxxxxxxxxxxxxx
Peter Duniho <NpOeStPeAdM@xxxxxxxxxxxxxxxx> wrote:
What I want is for player[i] to 'be' a PokerPlayer within the
PokerTable
class without having to cast it every time. I wouldn't mind so much if
CardPlayer[] player could be cast to PokerPlayer[] but I can't get that
to work.

Any ideas how to implement this idea?

The simplest method I see based on your current design would be to add a
new property that you use to alias the original array:

<snip>

Alternatively, you could provide a method that retrieves a specific index
and does the casting for you:

<snip>

If you're using .NET 2.0, you could make CardTable generic:

public class CardTable<T> where T : CardPlayer

then use "T" everywhere in CardTable, and declare PokerTable like this:

public class PokerTable : CardTable<PokerPlayer>


Thanks guys, I like the generic idea I will try that and see how far I get
with it.

Btw using a property to alias the original array like this:

public PokerPlayer[] pokerplayers
{
get { return (PokerPlayer[])player; }
}

doesn't work, I already tried it a few times in different forms. It
compiles ok but I get an InvalidCastException at runtime, 'Unable to cast
object of type 'CardPlayer[]' to type 'PokerPlayer[]'.'


.



Relevant Pages

  • Re: Inheritance Problem
    ... class without having to cast it every time. ... I wouldn't mind so much if ... public class PokerTable: CardTable ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Generic ICloneable
    ... ICloneablethen the object should be an X and you can cast directly to ... public X Clone() {... ... If you had a generic IClonable interface, ... public class MyClass: IClonable ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: S02E04 - Best episode yet...
    ... Simon Brooke writes: ... <snip stuff that I agree with but don't have anything to add> ... cast - you could easily believe in her as someone sexy because ... but turned it down in favour of acting. ...
    (uk.media.tv.sf.drwho)
  • Re: Casting generic collections & inheritance
    ... public class B: A { ... >> convert (for Lists, at least from one type to another). ... > converter that can always do an identity conversion (i.e. convert from ... >> just a simple cast from Farmer to Person. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Object casting (newbie)
    ... > what happens if I cast my child object to the parent objects? ... > If I cast a long to a byte I lose data. ... > public class child1 extendes cParent{ ... > public int getValue() { ...
    (comp.lang.java.programmer)

Quantcast