C# event issue resolved


Home | Blog | CSLA .NET | CSLA Store

06 January 2005

OK, I figured it out (I think)

<?xml:namespace prefix = o ns = “urn:schemas-microsoft-com:office:office” /> 

    [NonSerialized]     EventHandler _nonSerializableHandlers;     EventHandler _serializableHandlers;      

/// <summary>

   

/// Declares a serialization-safe IsDirtyChanged event.

   

/// </summary>

   

public event EventHandler IsDirtyChanged

    {       add       {        

if (value.Target.GetType().IsSerializable)

          _serializableHandlers =              (EventHandler)Delegate.Combine(_serializableHandlers,

value);

       

else

          _nonSerializableHandlers =              (EventHandler)Delegate.Combine(_nonSerializableHandlers,

value);

      }       remove       {        

if (value.Target.GetType().IsSerializable)

          _serializableHandlers =             (EventHandler)Delegate.Remove(_serializableHandlers,

value);

       

else

          _nonSerializableHandlers =             (EventHandler)Delegate.Remove(_nonSerializableHandlers,

value);

      }     }      

/// <summary>

   

/// Call this method to raise the IsDirtyChanged event.

   

/// </summary>

   

virtual protected void OnIsDirtyChanged()

    {      

if (_nonSerializableHandlers != null)

        _nonSerializableHandlers(

this, EventArgs.Empty);

     

if (_serializableHandlers != null)

        _serializableHandlers(

this, EventArgs.Empty);

    }   I temporarily forgot that C# makes you invoke the delegate directly anyway, so having a separate clause in the manual event declaration isn’t required. I still think it makes the code easier to read, but functionality is king in the end.