473,320 Members | 2,048 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,320 software developers and data experts.

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(string 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)Document.Load(FileName);
}
}

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 #1
64 3379
How can something be broken when it functions as designed?

You also assume that a common scenario in C++ would be common in C#,
which is not a very good assumption either.

My answer would be create a static factory class which instantiates the
proper subclass. That is a pretty old pattern, predating C# or Java,
and you'd probably want to use it in C++ as well.

On Jan 26, 12:06 pm, gro...@isaacsoft.com wrote:
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(string 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)Document.Load(FileName);
}

}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 #2
Just a word of advice.

When posting on a newgroup of c#, don't come out with statements like 'c#
inheritence broken' just because you don't know the c# way of doing
something you are used to.

Better to say i can do this in c++ but can't seem to find a comparative
solution in c#, here is my problem etc etc. You'll find you get a much
better response.

<gr****@isaacsoft.comwrote in message
news:11*********************@a75g2000cwd.googlegro ups.com...
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(string 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)Document.Load(FileName);
}
}

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 #3
Andy,

Thanks for your response. My assertion is that the DESIGN is broken!
But I'll settle for a work-around, if there is one.

If I understand your suggestion, I've already tried this. But...I
don't have any problem creating a new MyDocument object when I need it;
my problem is loading a MyDocument from a file. There is only one
method in Document that does this:

class Document
{
public static Document Load(string FileName);
}

I can certainly write a new Load method to override the base method, as
follows:

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

The problem is, the above code won't compile, because it is not valid
to cast the Document returned by Document.Load to a MyDocument.

Does that make sense?

Tony

On Jan 26, 11:31 am, "Andy" <a...@med-associates.comwrote:
How can something be broken when it functions as designed?

You also assume that a common scenario in C++ would be common in C#,
which is not a very good assumption either.

My answer would be create a static factory class which instantiates the
proper subclass. That is a pretty old pattern, predating C# or Java,
and you'd probably want to use it in C++ as well.

On Jan 26, 12:06 pm, gro...@isaacsoft.com wrote:
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(string 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)Document.Load(FileName);
}
}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?- Hide quoted text -- Show quoted text -
Jan 26 '07 #4
Hi,

<gr****@isaacsoft.comwrote in message
news:11*********************@a75g2000cwd.googlegro ups.com...
| 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

Jan 26 '07 #5
Hi,

"Andy" <an***@med-associates.comwrote in message
news:11**********************@v45g2000cwv.googlegr oups.com...
| How can something be broken when it functions as designed?
|
| You also assume that a common scenario in C++ would be common in C#,
| which is not a very good assumption either.
|
| My answer would be create a static factory class which instantiates the
| proper subclass. That is a pretty old pattern, predating C# or Java,
| and you'd probably want to use it in C++ as well.

I thikn that in the OP case either the writter of Document wrote it as a
"sealed" class or simply made an error. The class is clearly not creatable
and apparentely is also not derivable ( sealed )

It has nothing to do with C# capabilities.
Jan 26 '07 #6
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.comwrote:
Hi,

<gro...@isaacsoft.comwrote in messagenews:11*********************@a75g2000cwd.go oglegroups.com...
| 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
Jan 26 '07 #7
Hi,

<gr****@isaacsoft.comwrote in message
news:11**********************@q2g2000cwa.googlegro ups.com...
| Andy,
|
| Thanks for your response. My assertion is that the DESIGN is broken!

There is nothing wrong with teh design of C#.
What is broken is the design of the class you are trying to use :)

| But I'll settle for a work-around, if there is one.
|
| If I understand your suggestion, I've already tried this. But...I
| don't have any problem creating a new MyDocument object when I need it;
| my problem is loading a MyDocument from a file. There is only one
| method in Document that does this:
|
| class Document
| {
| public static Document Load(string FileName);
| }
Bad Design maybe?

If you do this you are certainly limiting yourself in that no derived class
will be able to override Load()

| I can certainly write a new Load method to override the base method, as
| follows:
|
| class MyDocument : Document
| {
| public static MyDocument Load(string FileName)
| {
| return Document.Load(FileName);
| }
| }
|
| The problem is, the above code won't compile, because it is not valid
| to cast the Document returned by Document.Load to a MyDocument.
|
| Does that make sense?
YES, and let me tell that again YES, IT DOES !

Not only that but it's the same IN ALL OTHER OOP LANGUAGES.
a MyDocument is a Document, the opposite (what you are trying to do) is not
true.

--
Ignacio Machin
machin AT laceupsolutions com
Jan 26 '07 #8


<gr****@isaacsoft.comwrote in message
news:11**********************@v45g2000cwv.googlegr oups.com...
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
Jan 26 '07 #9
Hi,
"Mythran" <ki********@hotmail.comwrote in message
news:e8**************@TK2MSFTNGP04.phx.gbl...
|
|
| <gr****@isaacsoft.comwrote in message
| news:11**********************@v45g2000cwv.googlegr oups.com...
| 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.

As I said in another post, giving the struct you are presenting you would
have the same issue no matter what language you use. You cannot treat a base
class as a derived class, you can do the opposite though.
In your case you will have to implement your own Load method. I would first
check though if Document provide a Load method instance. or maybe a Clone
method
--
Ignacio Machin
machin AT laceupsolutions com

Jan 26 '07 #10

"Ignacio Machin ( .NET/ C# MVP )" <machin TA laceupsolutions.comwrote in
message news:%2***************@TK2MSFTNGP06.phx.gbl...
Hi,
"Mythran" <ki********@hotmail.comwrote in message
news:e8**************@TK2MSFTNGP04.phx.gbl...
|
|
| <gr****@isaacsoft.comwrote in message
| news:11**********************@v45g2000cwv.googlegr oups.com...
| 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.

As I said in another post, giving the struct you are presenting you would
have the same issue no matter what language you use. You cannot treat a
base
class as a derived class, you can do the opposite though.
In your case you will have to implement your own Load method. I would
first
check though if Document provide a Load method instance. or maybe a Clone
method
--
Ignacio Machin
machin AT laceupsolutions com
This isn't a C# issue. It is a dotNet issue as I have run into the same
issue of inheriting a base class (in my case, VB 2005 and StringCollection)
and providing a method for the base class object to become the object at the
heart of the derived class. This is a design limitation in the framework
itself. From a business logic perspective, it should be doable.

Mike Ober.
Jan 26 '07 #11

On Jan 26, 1:21 pm, gro...@isaacsoft.com wrote:
Thanks for your response. My assertion is that the DESIGN is broken!
But I'll settle for a work-around, if there is one.
The design can't be broken, by definition. The design dictates how a
piece of software should function, and C# functions as designed. Now,
you may disagree with the design decision, and that's another topic,
but to say its broken is wrong. Is a Toyota car's design broken
because it doesn't have as much horsepower as my car? No.
If I understand your suggestion, I've already tried this. But...I
don't have any problem creating a new MyDocument object when I need it;
my problem is loading a MyDocument from a file. There is only one
method in Document that does this:

class Document
{
public static Document Load(string FileName);

}I can certainly write a new Load method to override the base method, as
follows:

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

}The problem is, the above code won't compile, because it is not valid
to cast the Document returned by Document.Load to a MyDocument.

Does that make sense?
Not at all. You should be coding to abstracts. If you really need
MyDocument, then you'll instantiate MyDocument and not the base class.

If you want that code to work, its pretty simple:

public static MyDocument Load(string FileName)
{
MyDocument result;

result = new MyDocument();
DocumentLoader.Load( result, FileName );

return result;
}

The loading of your document is now abstracted away from the document
itself, which is a good thing.

Jan 26 '07 #12
Ahh, good point. In that case, I would direct the OP to read up on why
the sealed keyword is even needed.

On Jan 26, 1:30 pm, "Ignacio Machin \( .NET/ C# MVP \)" <machin TA
laceupsolutions.comwrote:
Hi,

I thikn that in the OP case either the writter of Document wrote it as a
"sealed" class or simply made an error. The class is clearly not creatable
and apparentely is also not derivable ( sealed )

It has nothing to do with C# capabilities.
Jan 26 '07 #13
Ignacio,

There is no Load instance method in Document. Even if it had a Clone
method, this would cost too much time. As I pointed out before, C++
does indeed allow you to write such a "helper" class; you can use
reinterpret_cast to transform Document into a MyDocument.

Tony

On Jan 26, 1:13 pm, "Ignacio Machin \( .NET/ C# MVP \)" <machin TA
laceupsolutions.comwrote:
Hi,

"Mythran" <kip_pot...@hotmail.comwrote in messagenews:e8**************@TK2MSFTNGP04.phx.gbl. ..
|
|| <gro...@isaacsoft.comwrote in message|news:11**********************@v45g2000cwv. googlegroups.com...
| 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.

As I said in another post, giving the struct you are presenting you would
have the same issue no matter what language you use. You cannot treat a base
class as a derived class, you can do the opposite though.

In your case you will have to implement your own Load method. I would first
check though if Document provide a Load method instance. or maybe a Clone
method

--
Ignacio Machin
machin AT laceupsolutions com
Jan 26 '07 #14
Andy,

In your example, where does

DocumentLoader.Load( result, FileName );

come from?

....and about the Toyota car, if they design one that requires you to
crawl underneath to start it, that design is broken. :-)

Tony

On Jan 26, 1:45 pm, "Andy" <a...@med-associates.comwrote:
On Jan 26, 1:21 pm, gro...@isaacsoft.com wrote:
Thanks for your response. My assertion is that the DESIGN is broken!
But I'll settle for a work-around, if there is one.The design can't be broken, by definition. The design dictates how a
piece of software should function, and C# functions as designed. Now,
you may disagree with the design decision, and that's another topic,
but to say its broken is wrong. Is a Toyota car's design broken
because it doesn't have as much horsepower as my car? No.


If I understand your suggestion, I've already tried this. But...I
don't have any problem creating a new MyDocument object when I need it;
my problem is loading a MyDocument from a file. There is only one
method in Document that does this:
class Document
{
public static Document Load(string FileName);
}I can certainly write a new Load method to override the base method, as
follows:
class MyDocument : Document
{
public static MyDocument Load(string FileName)
{
return Document.Load(FileName);
}
}The problem is, the above code won't compile, because it is not valid
to cast the Document returned by Document.Load to a MyDocument.
Does that make sense?Not at all. You should be coding to abstracts. If you really need
MyDocument, then you'll instantiate MyDocument and not the base class.

If you want that code to work, its pretty simple:

public static MyDocument Load(string FileName)
{
MyDocument result;

result = new MyDocument();
DocumentLoader.Load( result, FileName );

return result;

}The loading of your document is now abstracted away from the document
itself, which is a good thing.- Hide quoted text -- Show quoted text -
Jan 26 '07 #15


On Jan 26, 9:06 am, gro...@isaacsoft.com wrote:
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#.

<snip>

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

class MyDocument : public Document
{
public static MyDocument Load(string FileName)
{
return (MyDocument)Document.Load(FileName);
}
Now, I'll state first off that I'm not a C++ guru. I used it briefly.

That said, I'm having trouble imagining how this would work in any
language. Let me modify your example a bit:

class MyDocument : public Document
{
private int additionalFIeld = 15;

public static MyDocument Load(string FileName)
{
return (MyDocument)Document.Load(FileName);
}
}

So... you're telling me that C++ somehow, magically, knows that when
MyDocument.Load calls Document.Load it must allocate additional space
for the object for the fields that are a part of MyDocument but not
part of Document? How could it possibly know?

OR

Are you saying that in C++ you can cheat and cast a base type to a
derived type and get away with it so long as the derived type has no
additional fields? (And so, by inference, if the derived type _does_
have additional fields then the cast still works but all hell breaks
loose at runtime?)

If you're suggesting the latter, then from a .NET point of view it is
C++ that is "broken". .NET was explicitly designed to _not_ allow
programmers to play fast and loose with objects. The whole idea is to
_guarantee_ that casts are valid, and that pointers point to the right
thing, so as to mitigate all sorts of hacking attacks that depend upon
overlaying memory that contains one thing with a definition for a
different thing and then having a field day with arbitrary operations
in memory.

For example, the following is perfectly legal C:

char x[4];
int *p = (int *)&x;
int y = *p;

Memory is plastic in C/C++: you can flip between types and the compiler
assumes that you know what you're doing. In C#, the compiler assumes
nothing. The compiler / CLR combine to make solid guarantees about what
is what and what operations you're allowed to perform. As such, if you
want to stick to what's called "safe" code in C#, you can't play these
sorts of tricks. The compiler / runtime won't let you. There's nothing
broken about it: just different design goals.

Jan 26 '07 #16

On Jan 26, 3:07 pm, gro...@isaacsoft.com wrote:
Andy,

In your example, where does

DocumentLoader.Load( result, FileName );

come from?
You build it of course ;-)
...and about the Toyota car, if they design one that requires you to
crawl underneath to start it, that design is broken. :-)
No, again, you disagree with the design, but its not broken, as long as
you can in fact start the car.

Jan 26 '07 #17
Here is some more relevant information that I've just learned:

The Document.Load static method relies on System.Runtime.Serialization
to create a new Document object. Formatter.Deserialize returns an
object that is a Document, and this Document object can't be cast to a
MyDocument. Deserialization can't occur in a constructor, because the
Document object already exists, and you can't replace "this" with the
new Document object.

So it would seem that the limitation is there because of the way
serialization works, not because of a bad design on the part of the
author of Document.

Tony

On Jan 26, 2:07 pm, gro...@isaacsoft.com wrote:
Andy,

In your example, where does

DocumentLoader.Load( result, FileName );

come from?

...and about the Toyota car, if they design one that requires you to
crawl underneath to start it, that design is broken. :-)

Tony

On Jan 26, 1:45 pm, "Andy" <a...@med-associates.comwrote:
On Jan 26, 1:21 pm, gro...@isaacsoft.com wrote:
Thanks for your response. My assertion is that the DESIGN is broken!
But I'll settle for a work-around, if there is one.The design can't be broken, by definition. The design dictates how a
piece of software should function, and C# functions as designed. Now,
you may disagree with the design decision, and that's another topic,
but to say its broken is wrong. Is a Toyota car's design broken
because it doesn't have as much horsepower as my car? No.
If I understand your suggestion, I've already tried this. But...I
don't have any problem creating a new MyDocument object when I need it;
my problem is loading a MyDocument from a file. There is only one
method in Document that does this:
class Document
{
public static Document Load(string FileName);
}I can certainly write a new Load method to override the base method, as
follows:
class MyDocument : Document
{
public static MyDocument Load(string FileName)
{
return Document.Load(FileName);
}
}The problem is, the above code won't compile, because it is not valid
to cast the Document returned by Document.Load to a MyDocument.
Does that make sense?Not at all. You should be coding to abstracts. If you really need
MyDocument, then you'll instantiate MyDocument and not the base class.
If you want that code to work, its pretty simple:
public static MyDocument Load(string FileName)
{
MyDocument result;
result = new MyDocument();
DocumentLoader.Load( result, FileName );
return result;
}The loading of your document is now abstracted away from the document
itself, which is a good thing.- Hide quoted text -- Show quoted text -- Hide quoted text -- Show quoted text -
Jan 26 '07 #18
<gr****@isaacsoft.comwrote in message
news:11**********************@k78g2000cwa.googlegr oups.com...
As I pointed out before, C++
does indeed allow you to write such a "helper" class; you can use
reinterpret_cast to transform Document into a MyDocument.
Is this quite true? My understanding is that <reinterpret_castsimply
performs an explicitly unsafe case of a pointer. It doesn't transform
anything. In this case, if a Document is created, it can never be
"transformed" into another type.

///ark
Jan 26 '07 #19
>You build it of course ;-)

Hmmm...I'm not sure how that would happen. I'm still stuck with the
fact that the third-party component's Load method returns a Document,
which can't be converted to type MyDocument, even in DocumentLoader.

Tony

On Jan 26, 2:23 pm, "Andy" <a...@med-associates.comwrote:
On Jan 26, 3:07 pm, gro...@isaacsoft.com wrote:
Andy,
In your example, where does
DocumentLoader.Load( result, FileName );
come from?You build it of course ;-)
...and about the Toyota car, if they design one that requires you to
crawl underneath to start it, that design is broken. :-)No, again, you disagree with the design, but its not broken, as long as
you can in fact start the car.
Jan 26 '07 #20
Mark,

Yes, reinterpret_cast is indeed unsafe. But if there are no added
members, it works, as in CRect : RECT.

But this strays from what I'm hoping to accomplish.

How is it that serialization can magically create a Document object
through casting an "object" to "Document," but I'm not allowed to use
the same trick to create a MyDocument instead? The Serialization
classes don't know about Document while deserialization is occuring,
but it still lets you cast the return value of Deserialize into a
Document type. What is the trick they are using?

Tony

On Jan 26, 2:30 pm, "Mark Wilden" <mwil...@communitymtm.comwrote:
<gro...@isaacsoft.comwrote in messagenews:11**********************@k78g2000cwa.g ooglegroups.com...
As I pointed out before, C++
does indeed allow you to write such a "helper" class; you can use
reinterpret_cast to transform Document into a MyDocument.Is this quite true? My understanding is that <reinterpret_castsimply
performs an explicitly unsafe case of a pointer. It doesn't transform
anything. In this case, if a Document is created, it can never be
"transformed" into another type.

///ark
Jan 26 '07 #21


On Jan 26, 12:53 pm, gro...@isaacsoft.com wrote:
Mark,

Yes, reinterpret_cast is indeed unsafe. But if there are no added
members, it works, as in CRect : RECT.

But this strays from what I'm hoping to accomplish.

How is it that serialization can magically create a Document object
through casting an "object" to "Document," but I'm not allowed to use
the same trick to create a MyDocument instead?
Because .NET doesn't trust you. :-)

One of the goals of .NET was to produce code that was immune to the
sort of run-time memory hacking that is rampant in C and C++. If the
runtime lets you play tricks like reinterpret_cast, then the code can't
be verifiably safe, can it?

As I said in my other post: different design goals. One goal of C++ was
to give the programmer total power to do whatever he wants, and the
compiler will trust him to get it right (by generating code no matter
what it might do at runtime). One goal of C# is to produce only code
that can be verified to not clobber memory / reinterpret memory
patterns as that which they are not / etc.

The two design goals are, obviously, incompatible.

If you want to do this sort of thing in C#, you have to use the
"unsafe" keyword to tell the compiler / runtime to lay off, but even
then I'm not sure of just how far you can go with that, because I've
never used it.

Jan 26 '07 #22
Hi,

<gr****@isaacsoft.comwrote in message
news:11**********************@s48g2000cws.googlegr oups.com...
| >You build it of course ;-)
|
| Hmmm...I'm not sure how that would happen. I'm still stuck with the
| fact that the third-party component's Load method returns a Document,
| which can't be converted to type MyDocument, even in DocumentLoader.

You simply have a crappy component :)
Use other
--
Ignacio Machin
machin AT laceupsolutions com
Jan 26 '07 #23
Hi,

"Michael D. Ober" <obermd.@.alum.mit.edu.nospamwrote in message
news:45*********************@news.qwest.net...

| --
| Ignacio Machin
| machin AT laceupsolutions com
| >
| This isn't a C# issue. It is a dotNet issue as I have run into the same
| issue of inheriting a base class (in my case, VB 2005 and
StringCollection)
| and providing a method for the base class object to become the object at
the
| heart of the derived class.

Not at all, A base class cannot become a derived class, A derived class can
be treated as a base class without any problem.

Think about, what would hppen if the derived object add a new property,
clearly the base does not has it , so what can the compiler do in this
case??

| This is a design limitation in the framework

No, it's simply bad design of the base class, or trying to made a bad use of
the class.

Jan 26 '07 #24


On Jan 26, 11:36 am, "Michael D. Ober" <obermd.@.alum.mit.edu.nospam>
wrote:
"Ignacio Machin ( .NET/ C# MVP )" <machin TA laceupsolutions.comwrote in
messagenews:%2***************@TK2MSFTNGP06.phx.gbl ...
Hi,
"Mythran" <kip_pot...@hotmail.comwrote in message
news:e8**************@TK2MSFTNGP04.phx.gbl...
|
|
| <gro...@isaacsoft.comwrote in message
|news:11**********************@v45g2000cwv.googleg roups.com...
| 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.
As I said in another post, giving the struct you are presenting you would
have the same issue no matter what language you use. You cannot treat a
base
class as a derived class, you can do the opposite though.
In your case you will have to implement your own Load method. I would
first
check though if Document provide a Load method instance. or maybe a Clone
method
--
Ignacio Machin
machin AT laceupsolutions comThis isn't a C# issue. It is a dotNet issue as I have run into the same
issue of inheriting a base class (in my case, VB 2005 and StringCollection)
and providing a method for the base class object to become the object at the
heart of the derived class. This is a design limitation in the framework
itself. 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.

You can't use a base class instance as though it were a derived class
instance because the latter may have more fields than the former, and
so the base class instance doesn't have enough space to store the state
of the derived class.

There _are_ various strategies for using a base class instance as a
model for creating a derived class. Most of them, however, require some
coding. There's no "automatic" way of copying state from one instance
to another, which might be a nice addition.

Jan 27 '07 #25
On 26 Jan 2007 12:26:15 -0800, gr****@isaacsoft.com wrote:
>Here is some more relevant information that I've just learned:

The Document.Load static method relies on System.Runtime.Serialization
to create a new Document object. Formatter.Deserialize returns an
object that is a Document, and this Document object can't be cast to a
MyDocument. Deserialization can't occur in a constructor, because the
Document object already exists, and you can't replace "this" with the
new Document object.

So it would seem that the limitation is there because of the way
serialization works, not because of a bad design on the part of the
author of Document.

Tony
Taking a completely different tack, how easy would it be for you to
parse through the Serialized Document file and change it to whatever
the equivalent Serialized MyDocument file would look like?

Given that you are trying to upcast the derived class, which goes
against the design goals of C#, this might be an easier way to work
round your problem.

rossum

Jan 27 '07 #26
No, it's simply bad design of the base class, or trying to made a bad use of
the class.
OK, please enlighten me. What would be the proper design of the base
class? I see no way to inherit from such a base class, regardless of
the base class design!

Tony

On Jan 26, 4:44 pm, "Ignacio Machin \( .NET/ C# MVP \)" <machin TA
laceupsolutions.comwrote:
Hi,

"Michael D. Ober" <obermd.@.alum.mit.edu.nospamwrote in messagenews:45*********************@news.qwest.net ...

| --
| Ignacio Machin
| machin AT laceupsolutions com
| >
| This isn't a C# issue. It is a dotNet issue as I have run into the same
| issue of inheriting a base class (in my case, VB 2005 and
StringCollection)
| and providing a method for the base class object to become the object at
the
| heart of the derived class.

Not at all, A base class cannot become a derived class, A derived class can
be treated as a base class without any problem.

Think about, what would hppen if the derived object add a new property,
clearly the base does not has it , so what can the compiler do in this
case??

| This is a design limitation in the framework

No, it's simply bad design of the base class, or trying to made a bad use of
the class.
Jan 27 '07 #27

"Bruce Wood" <br*******@canada.comwrote in message
news:11**********************@a75g2000cwd.googlegr oups.com...
>

On Jan 26, 11:36 am, "Michael D. Ober" <obermd.@.alum.mit.edu.nospam>
wrote:
>"Ignacio Machin ( .NET/ C# MVP )" <machin TA laceupsolutions.comwrote
in
messagenews:%2***************@TK2MSFTNGP06.phx.gb l...
Hi,
"Mythran" <kip_pot...@hotmail.comwrote in message
news:e8**************@TK2MSFTNGP04.phx.gbl...
|
|
| <gro...@isaacsoft.comwrote in message
|news:11**********************@v45g2000cwv.googleg roups.com...
| 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.
As I said in another post, giving the struct you are presenting you
would
have the same issue no matter what language you use. You cannot treat a
base
class as a derived class, you can do the opposite though.
In your case you will have to implement your own Load method. I would
first
check though if Document provide a Load method instance. or maybe a
Clone
method
--
Ignacio Machin
machin AT laceupsolutions comThis isn't a C# issue. It is a dotNet
issue as I have run into the same
issue of inheriting a base class (in my case, VB 2005 and
StringCollection)
and providing a method for the base class object to become the object at
the
heart of the derived class. This is a design limitation in the framework
itself. 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.

You can't use a base class instance as though it were a derived class
instance because the latter may have more fields than the former, and
so the base class instance doesn't have enough space to store the state
of the derived class.

There _are_ various strategies for using a base class instance as a
model for creating a derived class. Most of them, however, require some
coding. There's no "automatic" way of copying state from one instance
to another, which might be a nice addition.
A generalized method of converting a base class into a derived class with
the knowledge that the derived class may still require some initialization
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.

Jan 27 '07 #28
<gr****@isaacsoft.comwrote:
No, it's simply bad design of the base class, or trying to made a bad use of
the class.

OK, please enlighten me. What would be the proper design of the base
class? I see no way to inherit from such a base class, regardless of
the base class design!
Instead of having a static method which returns a Document, create an
*instance* method which loads data into an existing instance. That's
the way XmlDocumentLoad works, for 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
Jan 27 '07 #29
What is wrong with this approach?

class MyDocument : Document
{
public void CopyFromDocument(Document Original)
{
foreach (System.Reflection.PropertyInfo Prop in
Original.GetType().GetProperties())
{
if (Prop.CanWrite)
{
Prop.SetValue(this, Prop.GetValue(Original, null),
null);
}
}
foreach (System.Reflection.FieldInfo Field in
Original.GetType().GetFields())
{
Field.SetValue(this, Field.GetValue(Original));
}
}
}

Something similar can be implemented in the base class and would be
inherited by your class. There may be a performance issue with
Reflection though.
Jan 27 '07 #30
A generalized method of converting a base class into a derived class with
the knowledge that the derived class may still require some initialization
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.

Jan 27 '07 #31
On 2007-01-27, Bruce Wood <br*******@canada.comwrote:
>A generalized method of converting a base class into a derived class with
the knowledge that the derived class may still require some initialization
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 28 '07 #32
Hi,
<gr****@isaacsoft.comwrote in message
news:11**********************@l53g2000cwa.googlegr oups.com...
>No, it's simply bad design of the base class, or trying to made a bad use
of
the class.

OK, please enlighten me. What would be the proper design of the base
class? I see no way to inherit from such a base class, regardless of
the base class design!
Take a look at ANY OOp design book
That is like 101 OOP design

Jan 28 '07 #33

<gr****@isaacsoft.comwrote in message
news:11*********************@a75g2000cwd.googlegro ups.com...
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(string 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)Document.Load(FileName);
}
}
To do that, you'd have to define a way to convert Document to MyDocument.
And whatever you do could be done as easily in C# as in C++ (unless you did
something unsafe like memcpy()).
Jan 28 '07 #34

"Jon Skeet [C# MVP]" <sk***@pobox.comwrote in message
news:MP************************@msnews.microsoft.c om...
<gr****@isaacsoft.comwrote:
No, it's simply bad design of the base class, or trying to made a bad
use of
the class.

OK, please enlighten me. What would be the proper design of the base
class? I see no way to inherit from such a base class, regardless of
the base class design!

Instead of having a static method which returns a Document, create an
*instance* method which loads data into an existing instance. That's
the way XmlDocumentLoad works, for example.
Or, if you don't want the "empty" instance to be created (not a problem for
XmlDocument, of course)

1. Write a constructor that takes the filename (or Stream, or Reader,
....) as an argument
2. Have the constructor documented as calling a protected method to load
the instance

You can now inherit by creating a similar constructor in the derived class
and optionally overriding the protected method (if, say, the derived class
extends the file's possible contents.)
Jan 28 '07 #35
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++.

On Jan 26, 7:16 pm, "Bruce Wood" <brucew...@canada.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.
Jan 28 '07 #36

"Andy" <aj*****@alum.rit.eduwrote in message
news:11*********************@a75g2000cwd.googlegro ups.com...
On Jan 26, 7:16 pm, "Bruce Wood" <brucew...@canada.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 28 '07 #37
No, it's simply bad design of the base class, or trying to made a bad use of
the class.
You say the base class is designed poorly. So what would a GOOD
design look like? The constraints are:
- Original 'Document' object has been serialized as a 'Document.'
- Reflection (to make a copy) is impractical because it is time-
intensive.
- Wrapping (MyDocument "contains" a Document" is impractical because
of the large numbers of methods that would have to be reproduced.

I assert again that given these constraints (which are not uncommon in
programming), the design of C# (or .NET) doesn't provide a good
answer.

Tony

On Jan 26, 4:44 pm, "Ignacio Machin \( .NET/ C# MVP \)" <machin TA
laceupsolutions.comwrote:
Hi,

"Michael D. Ober" <obermd.@.alum.mit.edu.nospamwrote in messagenews:45*********************@news.qwest.net ...

| --
| Ignacio Machin
| machin AT laceupsolutions com
| >
| This isn't a C# issue. It is a dotNet issue as I have run into the same
| issue of inheriting a base class (in my case, VB 2005 and
StringCollection)
| and providing a method for the base class object to become the object at
the
| heart of the derived class.

Not at all, A base class cannot become a derived class, A derived class can
be treated as a base class without any problem.

Think about, what would hppen if the derived object add a new property,
clearly the base does not has it , so what can the compiler do in this
case??

| This is a design limitation in the framework

No, it's simply bad design of the base class, or trying to made a bad use of
the class.
Jan 29 '07 #38
Jon,

Yes, this makes sense. But System.Serialization 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'.

Tony

On Jan 27, 2:26 am, Jon Skeet [C# MVP] <s...@pobox.comwrote:
<gro...@isaacsoft.comwrote:
No, it's simply bad design of the base class, or trying to made a bad use of
the class.
OK, please enlighten me. What would be the proper design of the base
class? I see no way to inherit from such a base class, regardless of
the base class design!Instead of having a static method which returns a Document, create an
*instance* method which loads data into an existing instance. That's
the way XmlDocumentLoad works, for example.

--
Jon Skeet - <s...@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
Jan 29 '07 #39

<gr****@isaacsoft.comwrote in message
news:11**********************@l53g2000cwa.googlegr oups.com...
>No, it's simply bad design of the base class, or trying to made a bad use
of
the class.

You say the base class is designed poorly. So what would a GOOD
design look like? The constraints are:
- Original 'Document' object has been serialized as a 'Document.'
- Reflection (to make a copy) is impractical because it is time-
intensive.
- Wrapping (MyDocument "contains" a Document" is impractical because
of the large numbers of methods that would have to be reproduced.

I assert again that given these constraints (which are not uncommon in
programming), the design of C# (or .NET) doesn't provide a good
answer.
But you haven't shown a C++ solution either, since the cast in your example
doesn't work.
Jan 29 '07 #40
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.rit.eduwrote in messagenews:11*********************@a75g2000cwd.go oglegroups.com...
On Jan 26, 7:16 pm, "Bruce Wood" <brucew...@canada.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****@isaacsoft.comwrote:
Yes, this makes sense. But System.Serialization 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.com>
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.comwrote:
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 ClassCastException.

--
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
Jan 29 '07 #43

"Jon Skeet [C# MVP]" <sk***@pobox.comwrote in message
news:MP************************@msnews.microsoft.c om...
Andy <an***@med-associates.comwrote:
>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 ClassCastException.
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.Ravichandran
- http://www.geocities.com/
jvravichandran
- Or, just search on "J.V.Ravichandran"
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.com>
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.Ravichandran
- http://www.geocities.com/
jvravichandran
- Or, just search on "J.V.Ravichandran"
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*********@comcastXXXXXXX.netwrote in message
news:Xq******************************@comcast.com. ..
On 2007-01-27, Bruce Wood <br*******@canada.comwrote:
>>A generalized method of converting a base class into a derived class
with
the knowledge that the derived class may still require some
initialization
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...@comcastXXXXXXX.netwrote in messagenews:Xq******************************@comca st.com...
On 2007-01-27, Bruce Wood <brucew...@canada.comwrote:
>A generalized method of converting a base class into a derived class
with
the knowledge that the derived class may still require some
initialization
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
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...
5
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. ...
19
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
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...
2
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 -...
6
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...
31
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...
2
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...
23
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
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

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.