473,386 Members | 1,621 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Inheritance Problem

Gaz
This is as barebones as I can get it in order to explain my problem.

************************************************** **************************
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
PokerTable t = new PokerTable();
Console.WriteLine(t.ToString());
Console.ReadLine();
}
}
}

public class CardPlayer
{
public string name;
}

public class PokerPlayer : CardPlayer
{
public int chips = 1000;
}

public class CardTable
{
public CardPlayer[] player;

public CardTable()
{
player = new CardPlayer[5];
fillseats();
for (int i = 0; i < player.Length; i++)
player[i].name = i.ToString();
}

protected virtual void fillseats()
{
for (int i = 0; i<player.Length; i++)
player[i] = new CardPlayer();
}

public override string ToString()
{
StringBuilder s = new StringBuilder();
for (int i = 0; i < player.Length; i++)
{
Console.WriteLine("Player " + player[i].name + ".");
}
return s.ToString();
}
}

public class PokerTable : CardTable
{
public PokerTable()
{
}

protected override void fillseats()
{
for (int i = 0; i < player.Length; i++)
player[i] = new PokerPlayer();
}

public override string ToString()
{
StringBuilder s = new StringBuilder();
for (int i = 0; i < player.Length; i++)
{
s.AppendLine("Player " + player[i].name + " has " +
((PokerPlayer)player[i]).chips + " chips.");
}
return s.ToString();
}
}
************************************************** **************************
A PokerTable 'is' a CardTable and a PokerPlayer 'is' a CardPlayer.

A CardTable 'has' CardPlayers and a PokerTable 'has' PokerPlayers.

The only annoying thing is that every time I want to refer to the
player[i].chips member within PokerTable, I have to explicitly cast
player[i] to a PokerPlayer first in order to get at it.

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?
Apr 30 '07 #1
9 1397
On Sun, 29 Apr 2007 21:03:58 -0700, Gaz <a@b.comwrote:
[...]
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:

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

Then whenever you want an array of PokerPlayer instances, you use
"pokerplayers" instead of "player".

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

public PokerPlayer PokerPlayerFromIndex(int i)
{
return (PokerPlayer)player[i];
}

Pete
Apr 30 '07 #2
Peter Duniho <Np*********@nnowslpianmk.comwrote:
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<Twhere T : CardPlayer

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

public class PokerTable : CardTable<PokerPlayer>

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Apr 30 '07 #3
Gaz
"Jon Skeet [C# MVP]" <sk***@pobox.comwrote in message
news:MP********************@msnews.microsoft.com.. .
Peter Duniho <Np*********@nnowslpianmk.comwrote:
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<Twhere 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[]'.'
Apr 30 '07 #4
On Mon, 30 Apr 2007 00:22:11 -0700, Gaz <a@b.comwrote:
[...]
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[]'.'
Huh. I could swear that worked when I tried it. Sorry if I offered bad
advice. My second option should work though for sure. :)

Oh well...I like Jon's generic idea better anyway. I tried casting a
generic array but couldn't get that to work. Making the whole class based
on a generic class seems like a reasonable alternative to me.

Pete
Apr 30 '07 #5
> public PokerPlayer[] pokerplayers
> {
get { return (PokerPlayer[])player; }
}
This is a common gotcha. PokerPlayer[] and CardPlayer[] are not related to
each other, even though their contents are.

///ark
May 2 '07 #6
Mark Wilden <mw*****@communitymtm.comwrote:
public PokerPlayer[] pokerplayers
{
get { return (PokerPlayer[])player; }
}

This is a common gotcha. PokerPlayer[] and CardPlayer[] are not related to
each other, even though their contents are.
No, that's not right. There's an implicit conversion from PokerPlayer[]
to CardPlayer[], but a CardPlayer[] doesn't become a PokerPlayer[] just
because all of its elements are PokerPlayers.

I suspect you're thinking of generics, where List<string*isn't*
convertible to List<object>.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
May 2 '07 #7
On Tue, 01 May 2007 23:34:17 -0700, Jon Skeet [C# MVP] <sk***@pobox.com>
wrote:
Mark Wilden <mw*****@communitymtm.comwrote:
>This is a common gotcha. PokerPlayer[] and CardPlayer[] are not related
to each other, even though their contents are.

No, that's not right. There's an implicit conversion from PokerPlayer[]
to CardPlayer[], but a CardPlayer[] doesn't become a PokerPlayer[] just
because all of its elements are PokerPlayers.
Well, that's why I was surprised that you get a run-time error on the
conversion.

After all, you can *explicitly* cast a CardPlayer to a PokerPlayer, as
long as that CardPlayer is indeed a PokerPlayer.

Likewise, it seems to me that the language ought to allow one to cast a
CardPlayer[] to a PokerPlayer[] as long as each member of the array is a
PokerPlayer. Conversely, if the language isn't going to allow that (to
prevent hidden performance pitfalls, for example), then it should emit a
compile-time error instead of waiting until runtime (which is what it does
with generics).

Basically, I don't see anything about the syntax of "PokerPlayer[]
pokerplayers = (PokerPlayer[])cardplayers;" that justifies the compiler
allowing it if it's just going to create a run-time error anyway. Is
there some scenario where the "cardplayers" variable could have been
down-cast from a "PokerPlayer[]" initially, and so the cast would work?

Pete
May 2 '07 #8
Actually, I think I was thinking of C++. :)
May 2 '07 #9
Peter Duniho <Np*********@nnowslpianmk.comwrote:
No, that's not right. There's an implicit conversion from PokerPlayer[]
to CardPlayer[], but a CardPlayer[] doesn't become a PokerPlayer[] just
because all of its elements are PokerPlayers.

Well, that's why I was surprised that you get a run-time error on the
conversion.

After all, you can *explicitly* cast a CardPlayer to a PokerPlayer, as
long as that CardPlayer is indeed a PokerPlayer.

Likewise, it seems to me that the language ought to allow one to cast a
CardPlayer[] to a PokerPlayer[] as long as each member of the array is a
PokerPlayer.
No - the array "knows" what kind it is and won't allow itself to be
downcast lower than that. Imagine if it did allow it, and consider this
example:

CardPlayer[] players = new CardPlayer[1];
players[0] = new PokerPlayer();
PokerPlayer[] pokerPlayers = (PokerPlayer[]) players;
players[0] = new WhistPlayer();

PokerPlayer pokerPlayer = players[0];

At that point, something really *bad* has happened... but it's not
clear where it should be. There shouldn't be any chance of the last
line going wrong, but that's the only place where it would make sense
to throw an exception, as prior to that there aren't any errors. But
you can't just let it go without any exceptions, as otherwise
pokerPlayer would be a reference to a WhistPlayer.
Conversely, if the language isn't going to allow that (to
prevent hidden performance pitfalls, for example), then it should emit a
compile-time error instead of waiting until runtime (which is what it does
with generics).
It can't emit a compile-time error, because you could do:

CardPlayer[] players = new PokerPlayer[5];
PokerPlayer[] pokerPlayers = (PokerPlayer[]) players;

No runtime exception.
Basically, I don't see anything about the syntax of "PokerPlayer[]
pokerplayers = (PokerPlayer[])cardplayers;" that justifies the compiler
allowing it if it's just going to create a run-time error anyway. Is
there some scenario where the "cardplayers" variable could have been
down-cast from a "PokerPlayer[]" initially, and so the cast would
work?
See the above example.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
May 2 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: AIM | last post by:
Error in msvc in building inheritance.obj to build hello.pyd Hello, I am trying to build the boost 1.31.0 sample extension hello.cpp. I can not compile the file inheritance.cpp because the two...
3
by: Morten Aune Lyrstad | last post by:
Hi again! I'm having problems with inheritance. I have a base interface class called IObject. Next I have two other interfaces classes, IControl and ICommandMaster, which derives from IObject. ...
14
by: Steve Jorgensen | last post by:
Recently, I tried and did a poor job explaining an idea I've had for handling a particular case of implementation inheritance that would be easy and obvious in a fully OOP language, but is not at...
22
by: Matthew Louden | last post by:
I want to know why C# doesnt support multiple inheritance? But why we can inherit multiple interfaces instead? I know this is the rule, but I dont understand why. Can anyone give me some concrete...
8
by: Gaetan | last post by:
hi i have 2 classes A1 and A2 implementing a problem with 2 different ways i also have 2 other classes X1 and X2 implementing an other problem i need classes that provide A1+X1 methods,...
6
by: VR | last post by:
Hi, I read about Master Pages in ASP.Net 2.0 and after implementing some WinForms Visual Inheritance I tryed it with WebForms (let's say .aspx pages, my MasterPage does not have a form tag itself...
60
by: Shawnk | last post by:
Some Sr. colleges and I have had an on going discussion relative to when and if C# will ever support 'true' multiple inheritance. Relevant to this, I wanted to query the C# community (the...
5
by: colint | last post by:
Hi I'm fairly new to c++ and I have a question regarding inheritance. I'm trying to create a class based on 2 inherited classes, e.g. class A { ... } class B: public A
5
by: a | last post by:
Hi, I have an oop inheritance graph problem. What is the difference betweent the following 2 inheritance graph? How does the C++ solve the naming conflict problem for multiple inheritance...
3
by: Leo Seccia | last post by:
Hello everyone, I have a c# project with a sql server database. I have a number of lookup tables in my database which I successfully managed to import into my LINQ dataclasses. eg. Table:...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.