Click to Rate and Give Feedback
MSDN
MSDN Library
.NET Development
.NET Framework 3.5
System Namespace

  Switch on low bandwidth view
This page is specific to
Microsoft Visual Studio 2008/.NET Framework 3.5

Other versions are also available for the following:
.NET Framework Class Library
NonSerializedAttribute Class

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

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)
Visual Basic (Declaration)
<ComVisibleAttribute(True)> _
<AttributeUsageAttribute(AttributeTargets.Field, Inherited := False)> _
Public NotInheritable Class NonSerializedAttribute _
    Inherits Attribute
Visual Basic (Usage)
Dim instance As NonSerializedAttribute
C#
[ComVisibleAttribute(true)]
[AttributeUsageAttribute(AttributeTargets.Field, Inherited = false)]
public sealed class NonSerializedAttribute : Attribute
Visual C++
[ComVisibleAttribute(true)]
[AttributeUsageAttribute(AttributeTargets::Field, Inherited = false)]
public ref class NonSerializedAttribute sealed : public Attribute
JScript
public final class NonSerializedAttribute extends Attribute

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.

Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows CE Platform Note:

The NonSerializedAttribute attribute is present in the .NET Compact Framework for compatibility only, and will be ignored if used.

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.

Visual Basic
Imports System
Imports System.IO
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters.Soap




Public Class Test

   Public Shared Sub Main()

      ' Creates a new TestSimpleObject object.
      Dim obj As New TestSimpleObject()

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

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



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

      ' Empties obj.
      obj = Nothing

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



      obj = CType(formatter.Deserialize(stream), TestSimpleObject)
      stream.Close()

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

   End Sub 'Main

End Class 'Test


' A test object that needs to be serialized.
<Serializable()> Public Class TestSimpleObject

   Public member1 As Integer
   Public member2 As String
   Public member3 As String
   Public member4 As Double

   ' A member that is not serialized.
   <NonSerialized()> Public member5 As String  


   Public Sub New()     
      member1 = 11
      member2 = "hello"
      member3 = "hello"
      member4 = 3.14159265
      member5 = "hello world!"
   End Sub 'New


   Public Sub 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)
   End Sub 'Print

End Class 'TestSimpleObject

C#
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);
    }
}

Visual C++
#using <system.dll>
#using <system.messaging.dll>
#using <System.Runtime.Serialization.Formatters.Soap.dll>

using namespace System;
using namespace System::IO;
using namespace System::Runtime::Serialization::Formatters::Soap;

// A test object that needs to be serialized.

[Serializable]
ref class TestSimpleObject
{
private:
   int member1;
   String^ member2;
   String^ member3;
   double member4;

public:

   // A field that is not serialized.

   [NonSerialized]
   String^ member5;
   TestSimpleObject()
   {
      member1 = 11;
      member2 = "hello";
      member3 = "hello";
      member4 = 3.14159265;
      member5 = "hello world!";
   }

   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 );
   }

};

int main()
{

   //Creates a new TestSimpleObject object.
   TestSimpleObject^ obj = gcnew 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 = gcnew SoapFormatter;

   //BinaryFormatter* formatter = new BinaryFormatter();
   formatter->Serialize( stream, obj );
   stream->Close();

   //Empties obj.
   obj = nullptr;

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

   //formatter = new BinaryFormatter();
   obj = dynamic_cast<TestSimpleObject^>(formatter->Deserialize( stream ));
   stream->Close();
   Console::WriteLine( "" );
   Console::WriteLine( "After deserialization the object contains: " );
   obj->Print();
}


System..::.Object
  System..::.Attribute
    System..::.NonSerializedAttribute
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

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

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Declaring an event to be unserialized      Greg D ... _VMI   |   Edit   |   Show History
It may occasionally be useful to serialize an object that exposes event without serializing all subscribers to the object's events. Unfortunately,
[NonSerialized]
public event EventHandler<EventArgs> PropertyChanged;
results in an error because NonSerializedAttribute only applies to fields. What to do?

There's a poorly documented, hackish feature that lets us work through this

[field: NonSerialized]
public event EventHandler<EventArgs> PropertyChanged;

The field prefix indicates that the attribute should apply only to the backing field.

Warning!

As far as I can tell, this is not an officially supported feature! If it is, I can't find it in the docs. This workaround should not be used in production code! Production code may benefit from the use of the "Memento" pattern, or something similar, to capture only the desired state.


... Umm... it's documented in the code right above.

Tags What's this?: Add a tag
Flag as ContentBug
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker