Mark Maguire

Mark Maguire

  • NA
  • 17
  • 17.8k

Serialization - Event causes an error

May 17 2011 4:51 AM

I have written a serializable class which worked perfectly until I implemented an event within it.

Looking at the code below you will see that I have created a list class called CustomRecordList, this class is derived from the List class in order to access its events (in this case its Add).

namespace Serialization
{
    public delegate void RecordReadEvent();

    [ComVisible(false)]
    [Serializable]
    [XmlRoot]
    public class RiskSet
    {
        [field:NonSerialized]
        public event RecordReadEvent evtRecordRead;

        private CustomRecordList<RiskRecord> oRiskRecords;

        public RiskSet()
        {
            this.oRiskRecords = new CustomRecordList<RiskRecord>();
            this.oRiskRecords.OnItemAdded += new CustomRecordList<RiskRecord>.ItemAdded(oRiskRecords_OnItemAdded);
        }

        [XmlElement(IsNullable = false)]
        public CustomRecordList<RiskRecord> RiskRecord
        {
            get { return this.oRiskRecords; }
            set { this.oRiskRecords = value; }
        }

        public void oRiskRecords_OnItemAdded(RiskRecord item)
        {
            evtRecordRead();  //THIS IS WHERE THE ERROR IS RAISED
        }
    }
}

NOTE: If I remove the call to raise the evtRecordRead event from the oRiskRecords_OnItemAdded method it work perfectly, only when it does call that event does it fail.

The error message (including InnerEception) I recieve is:

"There is an error in XML document (3, 2087). System.NullReferenceException: Object reference not set to an instance of an object.\r\n   at Serialization.RiskSet.oRiskRecords_OnItemAdded(RiskRecord item) in C:\\Documents and Settings\\markm\\Desktop\\SCYLLA C# - Investigation\\With Events - Serialization - SCYLLA Based - All string data types\\Serialization - SCYLLA Based\\RiskSet.cs:line 40\r\n   at Serialization.CustomRecordList`1.Add(T item) in C:\\Documents and Settings\\markm\\Desktop\\SCYLLA C# - Investigation\\With Events - Serialization - SCYLLA Based - All string data types\\Serialization - SCYLLA Based\\CustomRecordList.cs:line 20\r\n   at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderRiskSet.Read8_RiskSet(Boolean isNullable, Boolean checkType)\r\n   at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderRiskSet.Read9_RiskSet()"

QUESTION: How can I get this class to raise the evtRecordRead event withod causing the error.


Answers (4)