Joe Developer is working on a bowling program (again). Joe wrote the following code.
using System;
using System.Collections.Generic;
[Serializable]
class Bowlers
{
List<string> _bowlerList = new List<string>();
public void AddBowler(string name)
{
_bowlerList.Add(name);
EventHandler<BowlerAddedEventArgs> handler = BowlerAdded;
if (handler != null)
{
handler(this, new BowlerAddedEventArgs(name));
}
}
public event EventHandler<BowlerAddedEventArgs> BowlerAdded;
// ...
}
[Serializable]
class BowlerAddedEventArgs : EventArgs
{
public BowlerAddedEventArgs(string name)
{
Name = name;
}
public string Name;
}
Joe unit tested the code to within an inch of its life, so he was surprised when another developer wrote the following program, which throws an exception.
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
class Test
{
public static void Main()
{
Bowlers bowlers = new Bowlers();
string addedMessage = "Added bowler: {0}";
bowlers.BowlerAdded +=
delegate(object sender, BowlerAddedEventArgs e)
{
Console.WriteLine(addedMessage, e.Name);
};
bowlers.AddBowler("Bob");
bowlers.AddBowler("Jan");
bowlers.AddBowler("Ann");
using (MemoryStream stream = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, bowlers);
}
}
}
What's wrong?
Hint: the exception is a strange looking serialization exception.