How to Create the Serializable Attribute in C#
-
Use the
SoapFormatter
orSerializableAttribute
Class to Create the Serializable Attribute inC#
-
Use the
BinaryFormatter
to Create the Serializable Attribute inC#
-
Use the
XMLSerializer
to Create the Serializable Attribute inC#
In this tutorial, you will learn the three primary ways to enable the serializability of an attribute to precisely use them in C#. Attribute serialization is a process based on different steps to persist an attribute or object from the memory to a sequence of bits.
When you serialize a class in C#, it automatically affects all its elements, and only marked fields of attributes are not serialized, meaning you can save a complex data structure easily just by serializing the root object.
Hibernate
is an excellent modern-day architecture example of serializable attributes to store an object or attribute (for class serializable) in byte sizes and to transfer the object to another system whenever required to deserialize.
Use the SoapFormatter
or SerializableAttribute
Class to Create the Serializable Attribute in C#
Every attribute, either public or private, marked by SerializableAttribute
is auto-serialized unless the Iserializable
interface overrides the attribute serialization process. To exclude some attributes from the serialization process, the NonSerializedAttribute
is extremely helpful.
Marking the attributes SerializableAttribute
only applies when using the SoapFormatter
or the BinaryFormatter
and the XmlSerializer
; DataContractSerializer
and JaveScriptSerializer
does not support or even recognize it. The BinaryFormatter
class belongs to the System.Runtime.Serialization.Formatters.Binary
namespace, and the serializable attributes use Clipboard.SetData()
to be stored on the clipboard.
Attribute’s binary serialization is more efficient because of its optimized memory and time consumption; however, it’s not human-readable. On the other hand, SOAP serialization is not efficient or optimized but makes the C# code readable.
XML serialization is slightly different as it uses XmlIgnore
instead of NonSerialized
and ignores Serializable
because it lives in the System.Xml.Serialization
namespace. It can not serialize private class members.
// using `System.Runtime.Serialization` namespace is optional
using System;
using System.IO;
using System.Windows.Forms;
// required | essential namespace
using System.Runtime > Serialization.Formatters.Soap;
namespace serializable_attribute {
public partial class Form1 : Form {
[Serializable()]
public class test_class {
public int attribute_one;
public string attribute_two;
public string attribute_three;
public double attribute_four;
// the `attribute_five` as the fifth member is not serialized
[NonSerialized()]
public string attribute_five;
public test_class() {
attribute_one = 11;
attribute_two = "the lord of the rings";
attribute_three = "valerian steel";
attribute_four = 3.14159265;
attribute_five = "i am unserialized text!";
}
public void Print() {
// MessageBox.Show(attribute_five.ToString()); remember, object reference is NULL
string delimiter = " , ";
string messageBoxContent = String.Join(delimiter, attribute_one, attribute_two,
attribute_three, attribute_four, attribute_five);
MessageBox.Show(messageBoxContent);
}
}
public Form1() {
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e) {
test_class obj = new test_class();
Stream serialized_stream = File.Open(
"data.xml", FileMode.Open); // replace your `.xml` file location or let it be default
// define a new `SoapFormatter` object
SoapFormatter formatter_soap = new SoapFormatter();
// serialize the object with the stream
formatter_soap.Serialize(serialized_stream, obj);
serialized_stream.Close(); // close the stream
// obj = null; | optional
serialized_stream = File.Open("data.xml", FileMode.Open);
formatter_soap = new SoapFormatter();
// deserialize the stream w.r.t the serializable object
obj = (test_class)formatter_soap.Deserialize(serialized_stream);
// close the stream
serialized_stream.Close();
// print the serialized object
obj.Print();
}
}
}
Output:
11, the lord of the rings, valerian steel, 3.14159265 ,
Most importantly, the serialization runtime associates with each serializable class or attribute a version number (to deserialize after verification). The deserialization will only happen when the version number of a serializable attribute is correct.
A good programmer should always declare the version number explicitly because of its highly sensitive computation depending on compiler implementations which can result in an error during deserialization.
The serializable attributes can be stored or written into files; if you understand polymorphism, this can make very much sense. You can serialize an attribute or save its state by converting it into a stream of bytes to store it in memory, a database, or a file.
Attribute serialization is essential for sending it to a remote application by the web server, passing it from one domain to another, passing it through a firewall as a JSON or XML string, or maintaining security or user-specific information across applications.
Use the BinaryFormatter
to Create the Serializable Attribute in C#
The serialization process is important to decorate each class, interface, or structure with the Serializable
attribute in C#. Creating a FileStream
object with a valid and readable name is important to serialize an attribute.
A Serialize()
method can be crafted with the help of a BinaryFormatter
object. The BinaryFormatter.Deserialize()
method returns an object that must be cast to the appropriate type.
To fully learn the serialization process of objects or attributes, you have to understand the deserialization process.
The deserialization process of serializable attributes starts by setting the reference to null
and creating a completely new array from scratch to house the deserialized array of test objects. You will learn this in the following executable C# program, and you will also learn the SerializeNow()
and DeSerializeNow()
methods, respectively.
In general, attribute serialization consists of creating an instance of the serialized object location, creating a stream from the file object, creating an instance of the BinaryFormatter
, and finally calling the Serialize()
method.
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows.Forms;
namespace serializable_attribute {
public partial class Form1 : Form {
[Serializable()]
public class test_class {
public int attribute_one;
public string attribute_two;
public string attribute_three;
public double attribute_four;
// the `attribute_five` as the fifth member is not serialized
[NonSerialized()]
public string attribute_five;
public test_class() {
attribute_one = 11;
attribute_two = "the lord of the rings";
attribute_three = "valerian steel";
attribute_four = 3.14159265;
attribute_five = "i am unserialized text!";
}
public void Print() {
// MessageBox.Show(attribute_five.ToString()); remember, object reference is NULL
string delimiter = " , ";
string messageBoxContent = String.Join(delimiter, attribute_one, attribute_two,
attribute_three, attribute_four, attribute_five);
MessageBox.Show(messageBoxContent);
}
}
public Form1() {
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e) {
test_class obj = new test_class();
Stream serialized_stream = File.Open("data.xml", FileMode.Create);
BinaryFormatter formatter_binary = new BinaryFormatter();
formatter_binary.Serialize(serialized_stream, obj);
serialized_stream.Close();
// obj = null;
serialized_stream = File.Open("data.xml", FileMode.Open);
formatter_binary = new BinaryFormatter();
obj = (test_class)formatter_binary.Deserialize(serialized_stream);
serialized_stream.Close();
obj.Print();
}
}
}
Output:
11, the lord of the rings, valerian steel, 3.14159265 ,
Classes for binary or XML serialization and deserialization belong to the System.Runtime.Serialization
namespace, making it an essential part/component of the serialization process. Both XML and binary serializations can offer separate benefits.
Binary serialization of attributes uses socket-based network streams, and all its members are read-only, which can enhance its performance. On the other hand, XML serialization uses an XML stream that conforms to a particular XML Schema Definition language (XSD) document, resulting in strongly typed attributes with public properties.
Furthermore, you can also use the SerializableAttribute
for a serializable attribute to a type to indicate its ability to serialize or otherwise. It’s a good practice not to serialize attributes that contains a handle, pointer, or some other data structure related or connected to a particular condition or environment.
Use the XMLSerializer
to Create the Serializable Attribute in C#
It enables the object’s state persistence to disk in XML format. To use the XMLSerializer
in C#, you must import the System.Xml
and the System.Xml.Serialization
namespaces.
The StreamWriter
object can enable an object’s serialization. Most importantly, the creation of the Serialize()
and Deserialize()
methods are the same as above, but instead of using the BinaryFormatter
, you will use the XMLSerializer
.
You can find the .xml
file of the serialized attributes under your C# program’s bin
or debug
folder; you can observe the test class’s persisted state in XML encoding. The Xsd.exe
is a great executable program or a tool that works as the XML Schema Definition Tool to make classes based on the existing XSD (XML Schema Definition) document.
using System;
using System.IO;
using System.Xml.Serialization;
using System.Windows.Forms;
namespace serializable_attribute {
[Serializable]
public class XMLSerialize {
public XMLSerialize() {}
public XMLSerialize(string rank, string sol_name) {
this._rank = rank;
this._name = sol_name;
}
public string _rank { get; set; }
public string _name { get; set; }
public override string ToString() {
return (_rank + " " + _name);
}
}
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e) {
XMLSerialize[] ser_obj = new XMLSerialize[3];
ser_obj[0] = new XMLSerialize("Captain", "Floyyd");
ser_obj[1] = new XMLSerialize("Major", "Gerizmann");
ser_obj[2] = new XMLSerialize("Sec. Lef.", "Angel");
TextWriter obj_txtWriter = null;
obj_txtWriter = new StreamWriter("test.xml");
XmlSerializer obj_xmlSerl = new XmlSerializer(typeof(XMLSerialize[]));
obj_xmlSerl.Serialize(obj_txtWriter, ser_obj);
string delimiter = " , ";
string messageBoxContent = String.Join(delimiter, ser_obj[0], ser_obj[1], ser_obj[2]);
MessageBox.Show(messageBoxContent);
obj_txtWriter.Close();
obj_txtWriter = null;
}
}
}
Output:
Captain Floyyd, Major Gerizmann, Sec. Lef. Angel
In C#, the serialization of attributes can be of two types: basic and custom serialization. The basic serialization of attributes is easy because it uses .NET to auto-serialize the attributes, and its only requirement is that a class has the SerializableAttribute
attribute applied.
Custom serialization enables you to mark which objects to serialize. The class must be marked SerializableAttribute
and use the ISerializable
interface, and it can also be deserialized in a custom manner using the custom constructor.
The designer serialization of attributes is the rarest form of attribute serialization that involves a special attribute persistence associated with the development tool. It is a process of converting graphs into a source file to recover it, and graphs can contain markup or C# code, even SQL table information.
Most serializable attributes are technical .custom
instances; however, the SerializableAttribute
maps to a command line interface .class
flag (serializable). The System.SerializableAttribute
specifies the attribute’s ability to serialize.
It’s important to remember that it’s not necessary to use the NonSerializedAttribute
if the given type implements the System.Runtime.Serialization.ISerializable
interface, which indicates that a class provides its own methods of serialization and deserialization. This can be something like:
public sealed class SerializableAttribute : Attribute {public method SerializableAttribute();}
In this tutorial, you’ve learned every possible way to serialize attributes and modify the attribute’s serialization and deserialization in C#.
Hassan is a Software Engineer with a well-developed set of programming skills. He uses his knowledge and writing capabilities to produce interesting-to-read technical articles.
GitHub