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

1

7

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.

Entice answered 16/6, 2011 at 1:14 Comment(0)
K
7

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.

Klapp answered 16/6, 2011 at 1:32 Comment(3)
Hmmm...ok, so maybe the reason my test succeeded was I was implementing custom serializing. Now that I think of it, I think that's why. But if you do it your way with the default serializing, it will get an exception. Thanks!Entice
Oh, yeah. Custom serialization (and even some of the other built in serializers) ignore the [Serializable] attribute. They could probably make the question a bit clearer on that. :)Klapp
That's the problem with these test questions. They are mostly of the trick question variety than the how-much-do-you-know variety.Entice

© 2022 - 2024 — McMap. All rights reserved.