I recently have had to answer some coding exercises for a job interview but the following one has me stumped. I think that the code is supposed to be part of a web service used by a mobile app.
Q: What are potential problems with the code below? How would you fix it?
public class Service
{
public event EventHandler<EventArgs> ItemCreated;
private Dictionary<Guid, Listener> _listeners = new Dictionary<Guid, Listener>();
public Guid Login()
{
var listener = new Listener(this);
var token = Guid.NewGuid();
_listeners[token] = listener;
return token;
}
public void Logout(Guid token)
{
_listeners.Remove(token);
}
}
public class Listener
{
public Listener(Service service)
{
service.ItemCreated += OnItemCreated;
}
private void OnItemCreated(object sender, EventArgs e)
{ }
}
I have put the code into a project and it runs without any issues.
My best shot so far is that there doesn't seem to be anywhere that the Event is triggered, but because the code doesn't have any further explanation that would allow for a fix I am doubting if I am correct on that.
UPDATE
Thanks for the answers. I have updated with my suggested fix.
public void Logout(Guid token)
{
_listeners[token].Unsubscribe(this);
_listeners.Remove(token);
}
public class Listener
{
...
public void Unsubscribe(Service service)
{
service.ItemCreated -= OnItemCreated;
}
}