Downcasting from base to derived classes. When is it allowed???

  • Thread starter Thread starter Brett
  • Start date Start date
B

Brett

I have a class 'Sample'. From it I have derived a class SampleExt that
provides a couple more methods and properties. My app initially uses the
Sample class, but there is an area of the application where I need to access
the methods and properties in SampleExt. What I'm trying to do is cast a
Sample to a SampleExt reference, the compiler allows it but the runtime
throws an InvalidCastException.
For example:

Function Whatever (pSample as Sample)
Dim x as SampleExt

x = CType (pSample, SampleExt)
x.ExtendedMethod
End Function

I have read statements that say this is possible and others that say it is
not. Can anyone clear it up unequivocally for me. I swear I done this
before, but maybe I was always upcasting....

If you are just going to respond with "Why don't you just <fill in the
blank>" suggesting that I do this some other way please save your time. I
have specific reasons for wanting to do it this way and they are too complex
(and irrelevant to this discussion) to include them here.

Thanks in advance.
Brett
 
Hi Brett,

Brett said:
I have a class 'Sample'. From it I have derived a class SampleExt that
provides a couple more methods and properties. My app initially uses the
Sample class, but there is an area of the application where I need to access
the methods and properties in SampleExt. What I'm trying to do is cast a
Sample to a SampleExt reference, the compiler allows it but the runtime
throws an InvalidCastException.

You cannot cast an instance of a base class to an instance of a derived
class in .NET. The reason the compiler does not complain when you code
this...

x = CType (pSample, SampleExt)

...is because the compiler can't know what instance (if any) pSample is
actually referencing. It could be referencing an instance of SampleExt, in
which case the cast would succeed.

Regards,
Dan
 
Brett,
In addition to Daniel's comments.

You asked "When is downcasting from a base to derived class allowed?"

It is allowed when you have an instance of the derived class in a base class
variable.

Given:
Function Whatever (pSample as Sample)
Dim x as SampleExt

x = CType (pSample, SampleExt)
x.ExtendedMethod
End Function


If I call the above with:

WhatEver(New Sample)

The function will fail, as I don't really have a SampleExt object, I have a
Sample object

However! if I call the above with:

WhatEver(New SampleExt)

The function will succeed as you really have a SampleExt object!


Normally what I do in Whatever is to check the type of the variable before
attempting the downcast.
Function Whatever (pSample as Sample)

If TypeOf pSample Is SampleExt Then
Dim x as SampleExt
x = DirectCast(pSample, SampleExt)
x.ExtendedMethod
End If
End Function

This will avoid the exception. Other comments withheld per your request.

Hope this helps
Jay
 
Back
Top