This documentation is archived and is not being maintained.

Mark all non-serializable fields

TypeName

MarkAllNonSerializableFields

CheckId

CA2235

Category

Microsoft.Usage

Breaking Change

Non 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.

Imports System
Imports System.Runtime.Serialization

Namespace UsageLibrary

   Public Class Mouse

      Dim buttons As Integer 
      Dim scanTypeValue As String 

      ReadOnly Property NumberOfButtons As Integer 
         Get 
            Return buttons
         End Get 
      End Property 

      ReadOnly Property ScanType As String 
         Get 
            Return scanTypeValue
         End Get 
      End Property 

      Sub New(numberOfButtons As Integer, scanType As String)
         buttons = numberOfButtons
         scanTypeValue = scanType
      End Sub 

   End Class

   <SerializableAttribute> _ 
   Public Class InputDevices1

      ' Violates MarkAllNonSerializableFields. 
      Dim opticalMouse As Mouse 

      Sub New()
         opticalMouse = New Mouse(5, "optical") 
      End Sub 

   End Class

   <SerializableAttribute> _ 
   Public Class InputDevices2

      ' Satisfies MarkAllNonSerializableFields.
      <NonSerializedAttribute> _ 
      Dim opticalMouse As Mouse 

      Sub New()
         opticalMouse = New Mouse(5, "optical") 
      End Sub 

   End Class 

End Namespace
Show: