Export (0) Print
Expand All

NonSerializedAttribute Class

Indicates that a field of a serializable class should not be serialized. This class cannot be inherited.

System.Object
  System.Attribute
    System.NonSerializedAttribute

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)

[AttributeUsageAttribute(AttributeTargets.Field, Inherited = false)]
[ComVisibleAttribute(true)]
public sealed class NonSerializedAttribute : Attribute

The NonSerializedAttribute type exposes the following members.

  NameDescription
Public methodNonSerializedAttributeInitializes a new instance of the NonSerializedAttribute class.
Top

  NameDescription
Public propertyTypeIdWhen implemented in a derived class, gets a unique identifier for this Attribute. (Inherited from Attribute.)
Top

  NameDescription
Public methodEqualsInfrastructure. Returns a value that indicates whether this instance is equal to a specified object. (Inherited from Attribute.)
Public methodGetHashCodeReturns the hash code for this instance. (Inherited from Attribute.)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodIsDefaultAttributeWhen overridden in a derived class, indicates whether the value of this instance is the default value for the derived class. (Inherited from Attribute.)
Public methodMatchWhen overridden in a derived class, returns a value that indicates whether this instance equals a specified object. (Inherited from Attribute.)
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Top

  NameDescription
Explicit interface implemetationPrivate method_Attribute.GetIDsOfNamesMaps a set of names to a corresponding set of dispatch identifiers. (Inherited from Attribute.)
Explicit interface implemetationPrivate method_Attribute.GetTypeInfoRetrieves the type information for an object, which can be used to get the type information for an interface. (Inherited from Attribute.)
Explicit interface implemetationPrivate method_Attribute.GetTypeInfoCountRetrieves the number of type information interfaces that an object provides (either 0 or 1). (Inherited from Attribute.)
Explicit interface implemetationPrivate method_Attribute.InvokeProvides access to properties and methods exposed by an object. (Inherited from Attribute.)
Top

When using the BinaryFormatter or SoapFormatter classes to serialize an object, use the NonSerializedAttribute attribute to prevent a field from being serialized. For example, you can use this attribute to prevent the serialization of sensitive data.

The target objects for the NonSerializedAttribute attribute are public and private fields of a serializable class. By default, classes are not serializable unless they are marked with SerializableAttribute. During the serialization process all the public and private fields of a class are serialized by default. Fields marked with NonSerializedAttribute are excluded during serialization. If you are using the XmlSerializer class to serialize an object, use the XmlIgnoreAttribute class to get the same functionality. Alternatively, implement the ISerializable interface to explicitly control the serialization process. Note that classes that implement ISerializable must still be marked with SerializableAttribute.

To apply the NonSerializedAttribute class to an event, set the attribute location to field, as shown in the following C# code.

[field:NonSerializedAttribute()] 
public event ChangedEventHandler Changed;

If a field is not serialized, but it still requires a default value that must be supplied after deserialization, you can create a method that supplies the field with a value, then apply the OnDeserializedAttribute to the method.

For more information about using attributes, see Extending Metadata Using Attributes.

The following example demonstrates serialization of an object marked with the SerializableAttribute attribute, and the behavior of a field marked with the NonSerializedAttribute in the serialized object.

NoteNote

The code uses the SoapFormatter class to serialize the object. The class is found in the system.runtime.serialization.formatters.soap.dll, which is not loaded by default into a project. To run the code, you must add a reference to the DLL to your project.

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Soap;
//using System.Runtime.Serialization.Formatters.Binary; 

public class Test {
   public static void Main()  {

      //Creates a new TestSimpleObject object.
      TestSimpleObject obj = new TestSimpleObject();

      Console.WriteLine("Before serialization the object contains: ");
      obj.Print();

      //Opens a file and serializes the object into it in binary format.
      Stream stream = File.Open("data.xml", FileMode.Create);
      SoapFormatter formatter = new SoapFormatter();

      //BinaryFormatter formatter = new BinaryFormatter();

      formatter.Serialize(stream, obj);
      stream.Close();

      //Empties obj.
      obj = null;

      //Opens file "data.xml" and deserializes the object from it.
      stream = File.Open("data.xml", FileMode.Open);
      formatter = new SoapFormatter();

      //formatter = new BinaryFormatter();

      obj = (TestSimpleObject)formatter.Deserialize(stream);
      stream.Close();

      Console.WriteLine("");
      Console.WriteLine("After deserialization the object contains: ");
      obj.Print();
   }
}


// A test object that needs to be serialized.
[Serializable()]		
public class TestSimpleObject  {

    public int member1;
    public string member2;
    public string member3;
    public double member4;

    // A field that is not serialized.
    [NonSerialized()] public string member5; 

    public TestSimpleObject() {

        member1 = 11;
        member2 = "hello";
        member3 = "hello";
        member4 = 3.14159265;
        member5 = "hello world!";
    }


    public void Print() {

        Console.WriteLine("member1 = '{0}'", member1);
        Console.WriteLine("member2 = '{0}'", member2);
        Console.WriteLine("member3 = '{0}'", member3);
        Console.WriteLine("member4 = '{0}'", member4);
        Console.WriteLine("member5 = '{0}'", member5);
    }
}

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Show:
© 2014 Microsoft