NonSerializedAttribute in Serialization
here you can find the code No SerializationThis 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;public class dotseri {
public static void Main() {
Dotnetspider seriobj = new Dotnetspider ();
Console.WriteLine("Before serialization: ");
seriobj.Show();
Stream stream = File.Open("sample.xml", FileMode.Create);
SoapFormatter formatter = new SoapFormatter();
formatter.Serialize(stream, seriobj);
stream.Close();
seriobj = null;
stream = File.Open("data.xml", FileMode.Open);
formatter = new SoapFormatter();
seriobj = (Dotnetspider)formatter.Deserialize(stream);
stream.Close();
Console.WriteLine("");
Console.WriteLine("After deserialization: ");
seriobj.Show();
}
}
[Serializable()]
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);
}
}