InvalidCastException

  • Thread starter Thread starter Chris Li
  • Start date Start date
C

Chris Li

I have the following classes:

Public Class BaseClass
{
...
}

Public Class DerivedClass: BaseClass
{
...
}

The following code will throw out an InvalidCastException:

BaseClass base = new BaseClass();
DerivedClass derived = (DerivedClass)base;

What do I need to do to make the casting successfully?




*** Sent via Devdex http://www.devdex.com ***
Don't just participate in USENET...get rewarded for it!
 
Here, you are trying to cast a generic type (base) to a specifc type (derived), which can't be done using a simple cast. Try using Type Convertors.
 
Do you have that backward?

If you said
DerivedClass myderived = New DerivedClass();
BaseClass mybase = (BaseClass) myderived;

then I would understand you.

However, to do what you are trying to do does not make sense.

Say your derived class adds a method to the interface. Call it method "mm".

If you create a base object, and cast it to a derived type, then the
language should let you call the derived method "mm", right?

Now, let's say that the data needed by method "mm" was initialized in the
constructor of the derived class, WHICH YOU NEVER CALLED.

What should 'mm' do? If the language let's you do that, then I would not
use the language. My code could be forced into a situation that I could not
prepare for, except to totally abandon the concept of constructors, which is
wildly inefficient.

Thank goodness C# won't let you do this.

If you find a way, please tell me, so I can find a way to protect my code
from programmers who would use it!

--- Nick
 
Nick, you are providing a good point and I have to admit that I did not
provide enough information about this situation. In my case, the base
class and the derived class have the same signiture (property and
method). The derived does not add any new property or method. You might
question why I want to generate a derived class. Here is the answer:

I have a base class and 2 derive classes. They have the same signiture
but one of the properties is of Arraylist type. Depending on the type of
derived class, this Arraylist contain a different class.

But I want the ability to cast the base class to derived class. Maybe
the TypeConvert class provide the answer for me.




*** Sent via Devdex http://www.devdex.com ***
Don't just participate in USENET...get rewarded for it!
 
You want Generics, Chris. New feature of both C# 2.0 and Java 2.0... this
was already a feature of C++ that was overlooked in the release of C#.

Generics allow you to create classes that manage objects of a type where the
type is not known by the author of the generic class. The type is still
declared at design time, when the variable is declared, but one body of code
(one class) can be used to manage an arraylist where the arraylist manages a
list of elements of a type.

Google generics and c#

--- Nick
 
Back
Top