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".
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With