Re: C# inheritance broken?



Ignacio,

Thank you for your thoughts.

The Document class does have a public default constructor, and it is
not sealed. I have no problem creating a "new" Document object, or a
"new" MyDocument object, for that matter. What I can't do is "convert"
an existing Document object (such as the one returned by Document.Load)
into a MyDocument.

Tony

On Jan 26, 12:28 pm, "Ignacio Machin \( .NET/ C# MVP \)" <machin TA
laceupsolutions.com> wrote:
Hi,

<gro...@xxxxxxxxxxxxx> wrote in messagenews:1169831207.816914.59560@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
| C# is an impressive language...but it seems to have one big limitation
| that, from a C++ background, seems unacceptable.

Not a good start IMHO :)

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

Why not?

Now, if the class is declared as sealed or the only constructor it has is a
private default constructor, well then maybe the designer did not want that
the class to be inheritable in the first place :)

| 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(string FileName),

This is an indication that the class is not creatable, and the default
constructor is not public
Then we have two options:
1- it's declared protected:
protected void Document() {}
2- It's declared private
private void Document() {}

In the first case you can derive from Document without any problem, in the
later then or the designer was trying to avoid what you want to do or
simply made a mistake :)

| >From reading LOTS of posts on this group, the standard answers are:
|
| 1. "Wrap" the object, as follows:
| class MyDocument
| {
| protected Document TheDocument;
| }

Honestly I haven't worked in C++ in a while but I could bet that a similar
situation can be created in C++.

| In C++, I would do something like this:
|
| class MyDocument : public Document
| {
| public static MyDocument Load(string FileName)
| {
| return (MyDocument)Document.Load(FileName);
| }
| }

What if Document declare a private constructor? in this escenario there is
no way for MyDocyment to construct a Document and the compiler will complain
(the same escenario you have now in C# )

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

Yes, and I hope that my explanation is clear enough to see what you missed.
Post back if still have questions

--
Ignacio Machin
machin AT laceupsolutions com

.



Relevant Pages