Catching creation/destruction of serializable objects

C

cctv.star

I need to maintain certain data structure, shared by all instances of
a class, declared as [Serializable]. This data structure must change
whenever a new object is created or an existing object is destroyed.
So I declared a static field with [NonSerialized()] attribute.

Now I need to add some code into all places where objects are created
and destroyed. This class has 2 ctors: one default, and another taking
parameters. I've found out, to my surprise, that new instances are
created without the use of these 2 ctors (how?).

My question: where should I put my code that tracks object creation
and destruction for these serializable objects?
 
P

Peter Morris

Maybe you should have a "Data Structure" type class to which you add
multiple instances of your other class, adding/removing/reordering items in
the list changes the data structure.
 
C

cctv.star

Maybe you should have a "Data Structure" type class to which you add
multiple instances of your other class, adding/removing/reordering items in
the list changes the data structure.

If I were creating all this from scratch, I'd have done so.

But I've got quite a lot of existing code that uses these serializable
objects directly, so I want to keep the changes to a minimum. And for
that, I need to identify all places where such objects are created and
destroyed. I thought that it would be easier to do from inside this
class.
 
C

Chris Jobson

Peter Duniho said:
Well, I would have said the constructor. I'm puzzled by your description,
as my experience with the basic serialization API in .NET is that it
requires a default constructor to deserialize objects, and that
constructor is in fact called when an object is deserialized.

I think it depends on what type of serialization is being used. Binary
serialization (using the BinaryFormatter class) does NOT call the
constructor when deserializing. Although I've not tried it myself, I believe
you can mark a method to be called during or after deserialization by using
the OnDeserializingAttribute or OnDeserializedAttribute attributes. Try
searching for help on these attributes for more details.

Chris Jobson
 
M

Marc Gravell

Chris Jobson's post should get you sorted - but a minor point;
serialization applies to instances, so I doubt that the [NonSerialized]
on a *static* field makes any difference.

Marc
 

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