Serialization Inheritance: Is an exception thrown if the base class is not marked [Serializable]?

Taking a practical exam, the exam said that I got it wrong. The answer marked in yellow is the correct answer.

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

enter image description here

I really created a sample project with the Animal and Cat class that derives from it. I noted the Cat [Serializable] class, but the Animal class is not specified.

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

Is this a problem with the .NET version? The exam is 70-536, so it is aimed at 2.0.

+7
source share
1 answer

Yes, the base class must also be serializable. Some simple test codes:

  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, but it worked for you. Do you have the code you used? This file is in .net 4, but I donโ€™t think it has changed much between versions.

+6
source

All Articles