473,738 Members | 10,068 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C# inheritance broken?

C# is an impressive language...but it seems to have one big limitation
that, from a C++ background, seems unacceptable.

Here's the problem:

I have a third-party Document class. (This means I can't change the
Document class.) I want to extend this (inherit from Document) as
MyDocument, adding new events and application-specific methods and
properties.

I submit that this can't be done in C#.

Consider this example:

class MyDocument : public Document

This doesn't work because the only way to open an existing Document is
using the static method Document.Load(s tring FileName), which returns a
Document object. There doesn't seem to be any way to convert or cast a
Document object to a MyDocument object. There is therefore no way to
"Load" a MyDocument object!
>From reading LOTS of posts on this group, the standard answers are:
1. "Wrap" the object, as follows:
class MyDocument
{
protected Document TheDocument;
}

But...this means that I have to wrap EACH of the hundreds of methods
and properties needed to manipulate the Document object. This is
clearly a case for inheritance, to allow the base class properties and
methods to be automatically available, with enhancements from the
derived class.

2. In MyDocument.Load , call Document.Load, and then COPY all of
Document's members to MyDocument.

BUT, this is prohibitive because COPYING all of Document's members is
prohibitive in terms of run time, and also in terms of development
effort (lines of code, and therefore, potential bugs).

In C++, I would do something like this:

class MyDocument : public Document
{
public static MyDocument Load(string FileName)
{
return (MyDocument)Doc ument.Load(File Name);
}
}

So my conclusion is that C# inheritance is broken (in practice) because
of its strict type-checking, and no allowance for such a common
scenario.

Did I miss something?

Jan 26 '07
64 3471
The code was:

class Employee { }
class VP extends Employee { }

Employee emp;
VP vp;

emp = new Employee();

vp = (VP)emp;

The book was Teach yourself Java 2 SDK 1.5 in 21 days from Sams and it
indicated code similar to the above would compile just fine.

Is that not the case? Or is there some detail that they didn't
mention at that point in the book?

On Jan 28, 12:17 pm, "Mike Schilling" <a...@newsgroup .nospamwrote:
"Andy" <ajj3...@alum.r it.eduwrote in messagenews:11* *************** *****@a75g2000c wd.googlegroups .com...
On Jan 26, 7:16 pm, "Bruce Wood" <brucew...@cana da.comwrote:
>From a business logic perspective, it should be doable.For the record, no
language that
I know of lets you do this. C++ allows
you to pretend to do it via an unsafe cast, but you're not really
getting a derived object, just playing with a base class object as
though it were a derived object, which is fodder for disaster unless
you keep careful track of what you're doing.
Actually, I was reading a Java book this weekend, and it seems that
you can do that in Java, likely with the same problems you would
encounter in C++.Casts are safe in Java, just as they are in C#. (That should be stated the
other way around, of course.)
Jan 29 '07 #41
<gr****@isaacso ft.comwrote:
Yes, this makes sense. But System.Serializ ation doesn't allow this.
You cann't deserialize a stream into an already existing object.
Deserialization always creates a new object, and you can't assign the
newly deserialized object to 'this'.
Then you'll need to have something in the base class which allows you
to copy the data from an existing instance to a new one.

Think of serialization/deserialization as like dehydrating and
rehydrating vegetables - you wouldn't expect to dry out a carrot, then
rehydrate it and get a cauliflower!

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jan 29 '07 #42
Andy <an***@med-associates.comw rote:
The code was:

class Employee { }
class VP extends Employee { }

Employee emp;
VP vp;

emp = new Employee();

vp = (VP)emp;

The book was Teach yourself Java 2 SDK 1.5 in 21 days from Sams and it
indicated code similar to the above would compile just fine.
Yes, it will compile fine, because the compiler doesn't look carefully
enough to see that emp is bound to just be an Employee, not a VP.

However, it will fail at runtime with a ClassCastExcept ion.

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

"Jon Skeet [C# MVP]" <sk***@pobox.co mwrote in message
news:MP******** *************** *@msnews.micros oft.com...
Andy <an***@med-associates.comw rote:
>The code was:

class Employee { }
class VP extends Employee { }

Employee emp;
VP vp;

emp = new Employee();

vp = (VP)emp;

The book was Teach yourself Java 2 SDK 1.5 in 21 days from Sams and it
indicated code similar to the above would compile just fine.

Yes, it will compile fine, because the compiler doesn't look carefully
enough to see that emp is bound to just be an Employee, not a VP.

However, it will fail at runtime with a ClassCastExcept ion.
And notice that exactly the same is true in C# (mod the name of the
exception).
Jan 30 '07 #44
The Virtual constructor technique would allow this in C++, which you can
substitute with the Factory pattern in C#. There are some good examples
of the Factory pattern in C# on the web.

Or, you can also use a technique called Covariance in C# with the help
of delegates. More can be posted here if you are able to follow this far
and interested in using delegates in your code.

with regards,
J.V.Ravichandra n
- http://www.geocities.com/
jvravichandran
- Or, just search on "J.V.Ravichandr an"
at http://www.Google.com

*** Sent via Developersdex http://www.developersdex.com ***
Jan 30 '07 #45
Ravichandran J.V. <jv************ @yahoo.comwrote :
The Virtual constructor technique would allow this in C++, which you can
substitute with the Factory pattern in C#. There are some good examples
of the Factory pattern in C# on the web.

Or, you can also use a technique called Covariance in C# with the help
of delegates. More can be posted here if you are able to follow this far
and interested in using delegates in your code.
I fail to see how delegates are relevant here...

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jan 30 '07 #46
"Covariance permits a method with a derived return type to be used as
the delegate,..." (msdn)

"When a delegate method has a return type that is more derived than the
delegate signature, it is said to be covariant. " (msdn)

It is just a technique that can substitute the virtual constructor
technique. It is not as if delegates should not be suggested if the
topic is on inheritance, is it? In this context, delegates help in
achieving the kind of covariance that is desired.

with regards,
J.V.Ravichandra n
- http://www.geocities.com/
jvravichandran
- Or, just search on "J.V.Ravichandr an"
at http://www.Google.com

*** Sent via Developersdex http://www.developersdex.com ***
Jan 30 '07 #47
On Jan 30, 9:18 am, Ravichandran J.V. <jvravichand... @yahoo.com>
wrote:
"Covariance permits a method with a derived return type to be used as
the delegate,..." (msdn)
"When a delegate method has a return type that is more derived than the
delegate signature, it is said to be covariant. " (msdn)
Indeed. I know all this... but it's not relevant.
It is just a technique that can substitute the virtual constructor
technique. It is not as if delegates should not be suggested if the
topic is on inheritance, is it? In this context, delegates help in
achieving the kind of covariance that is desired.
The OP wants to use an instance of a base class as if it were an
instance of a derived class. I still fail to see how delegate
covariance is relevant - all it means is that if you could use a
delegate which specifies that it returns an instance of MyDocument as
if it's an instance of a delegate which specifies that it returns an
instance of Document. That's not at all the same as what the OP's
trying to do.

In particular, it in no way allows you to convert an object of one
type to another type.

Jon

Jan 30 '07 #48
Tom,

Do you have a an example of how to do this with reflection?

Mike Ober.

"Tom Shelton" <to*********@co mcastXXXXXXX.ne twrote in message
news:Xq******** *************** *******@comcast .com...
On 2007-01-27, Bruce Wood <br*******@cana da.comwrote:
>>A generalized method of converting a base class into a derived class
with
the knowledge that the derived class may still require some
initializatio n
would definitely be useful, even if you had to do it via a constructor
that
takes an object of the base class as it's argument. The missing syntax,
in
vb is

mybase = objBaseClass

In C# I think it would be

base = objBaseClass

In either case, since this is occurring in a constructor in place of the
base.New() or mybase.New statement, the programmer knows he still has to
instantiate and initialize all other private and protected objects in
the
derived class.

Mike Ober.

Agreed. That would be nice. I wouldn't need it often, but it would get
one out of some tricky corners. My only point was that the whole "I
have a base class instance and I want to treat it as though it were a
derived class instance" is completely unsafe and therefore runs
against the grain of what .NET is supposed to be all about. Being able
to copy state, though, would be handy.

Reflection :)

--
Tom Shelton

Jan 30 '07 #49
Jake Stevenson's posted an example earlier on this thread.

That's all fine, but it does not get around the cost of *copying* the
object.

I suppose that what I really want here is a sort of "reference"
constructor, something like the "Attach" method in ATL's CComPtr
class. Come to think of it, CComPtr actually "wraps" the interface
being used, but its wrapper is generated automatically by a
preprocessor. Too bad C# doesn't have an automatic wrapper generator
similar to the #import directive in C++!

Tony

On Jan 30, 7:55 am, "Michael D. Ober" <obermd.@.alum. mit.edu.nospam>
wrote:
Tom,

Do you have a an example of how to do this with reflection?

Mike Ober.

"Tom Shelton" <tom_shel...@co mcastXXXXXXX.ne twrote in messagenews:Xq* *************** **************@ comcast.com...
On 2007-01-27, Bruce Wood <brucew...@cana da.comwrote:
>A generalized method of converting a base class into a derived class
with
the knowledge that the derived class may still require some
initializati on
would definitely be useful, even if you had to do it via a constructor
that
takes an object of the base class as it's argument. The missing syntax,
in
vb is
>mybase = objBaseClass
>In C# I think it would be
>base = objBaseClass
>In either case, since this is occurring in a constructor in place of the
base.New() or mybase.New statement, the programmer knows he still has to
instantiate and initialize all other private and protected objects in
the
derived class.
>Mike Ober.
Agreed. That would be nice. I wouldn't need it often, but it would get
one out of some tricky corners. My only point was that the whole "I
have a base class instance and I want to treat it as though it were a
derived class instance" is completely unsafe and therefore runs
against the grain of what .NET is supposed to be all about. Being able
to copy state, though, would be handy.
Reflection :)
--
Tom Shelton- Hide quoted text -- Show quoted text -
Jan 30 '07 #50

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

Similar topics

37
2840
by: Mike Meng | last post by:
hi all, I'm a newbie Python programmer with a C++ brain inside. I have a lightweight framework in which I design a base class and expect user to extend. In other part of the framework, I heavily use the instance of this base class (or its children class). How can I ensure the instance IS-A base class instance, since Python is a fully dynamic typing language? I searched and found several different ways to do this:
5
1669
by: Robert Spoons | last post by:
Can you look over this code, preferably try it, and comment? I believe the 'extend' function below will allow you to use full 'class inheritance' in javascript, but I would like to verify it. The extend function allows the following: 1) inheriting from multiple classes, 2) inheriting an inherited classes inheritances (awkward to say), 3) inheriting appended prototype methods and properties of inhertited classes.
19
2343
by: qazmlp | last post by:
class base { // other members public: virtual ~base() { } virtual void virtualMethod1()=0 ; virtual void virtualMethod2()=0 ; virtual void virtualMethod3()=0 ;
14
12917
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 all obvious in VBA which lacks inheritance. I'm trying the explanation again now. I often find cases where a limited form of inheritance would eliminate duplication my code that seems impossible to eliminate otherwise. I'm getting very...
2
1540
by: Andrew Ducker | last post by:
I'm implementing a singleton using the example at: http://www.yoda.arachsys.com/csharp/singleton.html as a basis (second example). However - I have about 20 classes I wish to make singletons - and I don't want to duplicate the code in each one. The difficulty comes in the method that returns the singleton instance. In the example it's: if (instance == null) instance = new Class1(); return instance;
6
2537
by: Pascal Polleunus | last post by:
Hi, I'm wondering if there could be problems related to inheritance in the following scenario (with PostgreSQL 7.4.1)... 1 A-table, abstract. Max 10 B-tables that inherit from A, with sometimes some more columns than A. These are also abstracts.
31
1939
by: John W. Kennedy | last post by:
I quite understand about prototypes and not having classes as such, but I happen to have a problem involving blatant is-a relationships, such that inheritance is the bloody obvious way to go. I can think of several ad-hoc ways to achieve inheritance, but is there an accepted standard idiom? -- John W. Kennedy "But now is a new thing which is very old-- that the rich make themselves richer and not poorer, which is the true Gospel, for...
2
278
by: groups | last post by:
C# is an impressive language...but it seems to have one big limitation that, from a C++ background, seems unacceptable. Here's the problem: I have a third-party Document class. (This means I can't change the Document class.) I want to extend this (inherit from Document) as MyDocument, adding new events and application-specific methods and properties.
23
4612
by: Dave Rahardja | last post by:
Since C++ is missing the "interface" concept present in Java, I've been using the following pattern to simulate its behavior: class Interface0 { public: virtual void fn0() = 0; };
0
8969
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9335
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9263
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9208
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8210
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6053
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4570
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4825
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2193
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.