Make Person.GetObjectData a virtual method. Change Keycard.GetObjectData to override the method instead of shadowing the method, and have it call the base method.
[Serializable()]
public class Person : ISerializable
{
...
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Name", name);
}
...
}
[Serializable()]
public class Keycard : Person
{
...
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("Keynumber", mykey);
}
...
}
Your code will now work. However, you're creating Stream objects, which should be disposed of when you're finished with them. The simplest way to do that is with a using block[^].
Keycard k1 = new Keycard("John", 123);
BinaryFormatter bf = new BinaryFormatter();
using (Stream stream = File.Open("KeycardData.dat", FileMode.Create))
{
bf.Serialize(stream, k1);
}
k1 = null;
using (Stream stream = File.Open("KeycardData.dat", FileMode.Open))
{
k1 = (Keycard)bf.Deserialize(stream);
}
Console.WriteLine(k1);
Console.ReadLine();
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer