CA2235: Mark all non-serializable fields

 

For the latest documentation on Visual Studio 2017, see Visual Studio 2017 Documentation.

For the latest documentation on Visual Studio 2017, see CA2235: Mark all non-serializable fields on docs.microsoft.com.

TypeNameMarkAllNonSerializableFields
CheckIdCA2235
CategoryMicrosoft.Usage
Breaking ChangeNon Breaking

An instance field of a type that is not serializable is declared in a type that is serializable.

A serializable type is one that is marked with the System.SerializableAttribute attribute. When the type is serialized, a System.Runtime.Serialization.SerializationException exception is thrown if a type contains an instance field of a type that is not serializable.

To fix a violation of this rule, apply the System.NonSerializedAttribute attribute to the field that is not serializable.

Only suppress a warning from this rule if a System.Runtime.Serialization.ISerializationSurrogate type is declared that allows instances of the field to be serialized and deserialized.

The following example shows a type that violates the rule and a type that satisfies the rule.

using System;
using System.Runtime.Serialization;

namespace UsageLibrary
{
   public class Mouse
   {
      int buttons;
      string scanTypeValue;

      public int NumberOfButtons
      {
         get { return buttons; }
      }

      public string ScanType
      {
         get { return scanTypeValue; }
      }

      public Mouse(int numberOfButtons, string scanType)
      {
         buttons = numberOfButtons;
         scanTypeValue = scanType;
      }
   }

   [SerializableAttribute]
   public class InputDevices1
   {
      // Violates MarkAllNonSerializableFields.
      Mouse opticalMouse;

      public InputDevices1()
      {
         opticalMouse = new Mouse(5, "optical"); 
      }
   }

   [SerializableAttribute]
   public class InputDevices2
   {
      // Satisfies MarkAllNonSerializableFields.
      [NonSerializedAttribute]
      Mouse opticalMouse;

      public InputDevices2()
      {
         opticalMouse = new Mouse(5, "optical"); 
      }
   }
}

CA2236: Call base class methods on ISerializable types

CA2240: Implement ISerializable correctly

CA2229: Implement serialization constructors

CA2238: Implement serialization methods correctly

CA2237: Mark ISerializable types with SerializableAttribute

CA2239: Provide deserialization methods for optional fields

CA2120: Secure serialization constructors

Show: