Chris Capon <(E-Mail Removed)> wrote:
> Sorry. I may not have been clear in my original post. Perhaps the example
> function should have been more like:
>
> Base a = new Base();
> Derived b = (Derived)a; //*** this will fail as an invalid cast
> b.GetVal();
>
> The above code casts an error because "a" has been created as a Base object,
> not a Derived object. Attempting to cast "a" to the wrong type of object
> causes an exception. But...
>
> If the Derived class were to only add methods and properties, there should
> be no harm in making this cast. For all intensive purposes, a Derived object
> would look identical to a Base object in memory.
That doesn't mean it would be harmless though. It would behave
differently. If I pass you a reference to an instance of a base class,
I don't want you to be able to treat it as if it were an instance of a
derived class which might have radically different behaviour.
> To give you a real world example, take the XmlElement object for instance.
> It is created by calling XmlDocument.CreateElement(). Since an XmlElement
> can't be created on its own, there is no way to extend this class with new
> functionality. All you can do is wrapper a reference to it within another
> class.
Yup.
> Suppose though, there were a class modifier which said, "this derived class
> does not modify the base object so the two can be used interchangeably". You
> could then extend base objects without knowing anything about how they were
> created.
Well, I'm afraid you can't. Personally I've rarely found I've wanted to
do this, but I'm glad I can't from a security point of view. Treating
an object as if it were an instance of a different type sounds pretty
dangerous to me.
--
Jon Skeet - <(E-Mail Removed)>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too