thomas
thomas

Reputation: 1174

Implementing ISerializable unnecessary?

I'm having a hard time understanding the need for the ISerializable interface... I guess I'm missing something pretty important in this subject, so I'd appreciate it if somebody could give me a hand.

This works perfectly well -

[Serializable]
    class Student
    {
        public int age;
        public string name;

        public Student()
        {
            age = 0;
            name = null;
        }
    }
 class Program
    {
        public static void Main()
        {
            Stream stream = File.Open("Test123.txt", FileMode.Create);

            BinaryFormatter bf = new BinaryFormatter();

            Student s1 = new Student();
            s1.name = "Peter";
            s1.age = 50;
            bf.Serialize(stream, s1);

            stream.Close();

            Stream stream2 = File.Open("Test123.txt", FileMode.Open);

            Student s2 = (Student)bf.Deserialize(stream2);

            Console.WriteLine(s2.age);

        }

And it worked without implementing ISerializable and without overriding GetObjectData(). How so? What is the use of the interface then?

Thanks.

Upvotes: 1

Views: 1039

Answers (2)

aL3891
aL3891

Reputation: 6275

In addition to @Marcus answer, Serializable and ISerializable only apply for the *Formatter (typically, BinaryFormatter and SoapFormatter) serializers built into .Net

If the attribute is there but the interface is not, they will use reflection to find all the properties and their values.

Different serializers have different ways of customizing serialization (all though most have an option to just use reflection)

XmlSerializer for example has a different interface, IXmlSerializable and also doesn't check for the Serializable attribute. check out the docs for what ever serializer you're using to see what the story is. Wcf for example uses the DataContract attributes to determine how and what to serialize

Upvotes: 2

Marcus
Marcus

Reputation: 8669

Serializable uses default serialization. The point of the ISerializable interface is to override serialization so that you can have your own.

Upvotes: 5

Related Questions