Rule Definition
Every field of a serializable class must be either serializable or transient. Declaring non-transient fields of non-serializable type inside of a serializable class will result in an exception thrown during the serialization.
Remediation
Make the field type serializable or transient.
Violation Code Sample
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
class SomeType { }
namespace MyObjSerial
{
[Serializable()] //Set this attribute to all the classes that want to serialize
public class Employee
{
int EmpId;
string EmpName;
SomeType Type; //violation
//Default constructor
public Employee()
{
EmpId = 0;
EmpName = null;
Type = null;
}
}
}
Fixed Code Sample
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace MyObjSerial
{
[Serializable()]
class SomeType { }
[Serializable()]
class Employee
{
int EmpId;
string EmpName;
SomeType Type; //no violation
//Default constructor
public Employee()
{
EmpId = 0;
EmpName = null;
Type = null;
}
}
}
Reference
CISQ: ASCRMRLB03
Related Technologies
Technical Criterion
CWE-1070 - Serializable Data Element Containing non-Serializable Item Elements
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.