up cast to base

  • Thread starter Thread starter Jeff.Boeker
  • Start date Start date
J

Jeff.Boeker

Hello,

I have a base class that is serializable and a derived class that is
not. I want to pass the base class object to an external function that
requires a serializable object. How can I cleanly create a new
instance of the base class that copies the base class from the derived
object. I can use brute force and create a new function that copies
each member variable but I assume there's a better way.

CDerived derived;
CBase base = derived as CBase;
obj.Serialize(base); ->error not serializable

Thanks,
Jeff
 
I have a base class that is serializable and a derived class that is

How did you achieve this? Are you getting errors at compile- or
runtime? Did you use the serializable attribute on your baseclass? Or
did you implement GetObjectData from ISerializable in your baseclass? I
think the latter approach wil work and would be an alternative to
creating a baseclass and copying all the values.
 
Hi,

If the base class is serializable ( it implement ISerializable ) then the
derived class is too.

You can cast the derived instance to the base class:

externalmethod( (BaseClass) derived_instance)
 
My base class is serializable by attribute, i.e. [Serialiazble]
The run time error I get when calling the external function is "Type
CDerived' in Assembly 'Test, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null' is not marked as serializable".

I guess the external function is still looking at the derived class.
Casting when calling doesn't help. I implemented a copy constructor in
the base class and use that instance and it works but ideally I would
not have to create a copy.
 
Back
Top