up cast to base

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
 
M

Marc Vangrieken

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.
 
I

Ignacio Machin \( .NET/ C# MVP \)

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)
 
J

JBoeker

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top