not wanting to serialize an event

A

alexis rzewski

I have a design in place for a .NET app coded in C# in which the
business object drives the appearence of the UI and when the business
object experiences a change, it notifies the various UIs via events .

Problem is, when I tried serializing the business object to a file,
when traversing the tree of referenced objects, it found the event
targets, and tried to serialize my UI object (which is not
serializable). I then said to myself: "simple solution: mark that
event as non serializable" and went ahead to include the
NonSerializable attribute, but the compiler rejected that as saying
that such attribute applies only to "fields" (and I guess an event is
not a field).

Eventually I solved my problem by having a separate object declaring
the events and broadcasting the events, an object I called
EventNotifier, an instance of which is defined in my business object,
which forwards the requests to broadcast a change event to the
notifier object. In the code, I did mark this instance variable as
[NonSerializable], thus the EventNotifier and all of its target
objects (the UI classes) are never serialized.

Used SOAP serializer in C# 1.1.

It fixed the problem, but was wondering if others have better ideas.
 
D

Daniel Pratt

Hi Alex,

If you declare an event like this:

public event EventHandler SomeEvent;

then the adding/removing of subscribers is handled transparently.
Presumably there's a field somewhere that holds the event subscribers, but
you can't "see" it, so there's no way to slap an attribute onto it.. On the
other hand, you can do something like this:

[NonSerialized]
private EventHandler someEventHandler;
...
public event EventHandler SomeEvent
{
add {someEventHandler = someEventHandler + value;}
remove {someEventHandler = someEventHandler - value;}
}

Regards,
Daniel
 

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