Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialization inheritance: Will an exception be thrown if the base class isn't marked [Serializable]?

Taking a practice exam the exam said I got this one wrong. The answer marked in Yellow is the supposed correct answer.

In the following quote, the part marked in bold I think is wrong: "The Serializable attribute is not inherited by the derived classes, so if you only mark the Encyclopedia class with the Serializable attribute, the runtime will throw an exception when trying to serialize the Name field".

enter image description here

I actually created a sample project with an Animal class and a Cat class that derives from it. I marked the Cat class [Serializable] and the Animal class is not.

I was able to successfully serialize and deserialize the Cat class, including the Animal properties.

Is this a .NET version issue? The exam is 70-536, so it's targeting 2.0.

like image 239
richard Avatar asked Jun 16 '11 01:06

richard


1 Answers

Yes, the base class also needs to be serializable. Some easy test code:

  public class Animal
    {
        public Animal()
        {
            name = "Test";
        }
        public string name { get; set; }
    }

    [Serializable]
    public class Cat : Animal
    {
        public string color {get; set;}
    }


        var acat = new Cat();
        acat.color = "Green";
        Stream stream = File.Open("test.bin", FileMode.Create);
        BinaryFormatter bformatter = new BinaryFormatter();

        bformatter.Serialize(stream, acat);
        stream.Close();

When you try to serialize, you get this error:

Type 'SerializeTest.Animal' in Assembly 'SerializeTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.

edit - I notice that you did the same thing but it worked for you. Do you have the code you used? This one is in .net 4, but I don't think its changed that much between versions.

like image 73
Tridus Avatar answered Sep 23 '22 05:09

Tridus