NonSerializedAttribute in Serialization

This example helps to prevent the filed from serialization.

To prevent the field from being serialized,when using BinaryFormatter or SoapFormatter classes to serialize an object, we can use NonSerializedAttribute

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

here you can find the code No Serialization

public class dotseri {
public static void Main() {

Dotnetspider seriobj = new Dotnetspider ();

Console.WriteLine("Before serialization: ");
Stream stream = File.Open("sample.xml", FileMode.Create);
SoapFormatter formatter = new SoapFormatter();

formatter.Serialize(stream, seriobj);

seriobj = null;

stream = File.Open("data.xml", FileMode.Open);
formatter = new SoapFormatter();

seriobj = (Dotnetspider)formatter.Deserialize(stream);

Console.WriteLine("After deserialization: ");

public class Dotnetspider {

public int Sno;
public string Name;
public string Address1;

[NonSerialized()] public string Address2;

// Address2 is not serialized
public Dotnetspider() {

Sno = 11;
Name = "sri";
Address1 = "5th st";
Address2 = "chennai";


public void Show() {

Console.WriteLine("Sno = '{0}'", Sno);
Console.WriteLine("Name = '{0}'", Name);
Console.WriteLine("Address1 = '{0}'", Address1);
Console.WriteLine("Address2 = '{0}'", Address2);


No responses found. Be the first to comment...

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: