juniorgarcia juniorgarcia - 3 years ago 154
C# Question

C# - Events for simple class

I'm struggling to understand how events works on C#. By now, I'm testing only in console applications. I've tried sometimes by what I read in the MSDN documentation, but unsuccessfully.

Here's is my code:

using System;
using System.Collections.Generic;

namespace Events
class MainClass
public static void Main(string[] args)
TodoList list = new TodoList();
TodoItem fooItem = new TodoItem
Title = "FooItemTitle",
Description = "FooItemDescription",

TodoItem barItem = new TodoItem
Title = "BarItemTitle",
Description = "BarItemDescription",

// I want to trigger an event everytime a item is added on the
// TodoList.
// How can I do that?

class TodoList
List<TodoItem> items;
public TodoList()
this.items = new List<TodoItem>();

public void AddItem(TodoItem item)

class TodoItem
public String Description;
public String Title;

public override string ToString()
return string.Format("[TodoItem]: Title={0} | Description={1}", this.Title, this.Description);

How would I configure an event to be triggered everytime a
is added on a

Answer Source

You can add an event to ToDoList:

// note how we assigned a blank delegate to it 
// this is to avoid NullReferenceException when we fire event with no subscribers

public event EventHandler<TodoItem> ItemAdded = (s, e) => { };

And trigger it inside of Add method:

ItemAdded(this, item);

Also don't forget to subscribe to event from some other class:

// as eventhandler you should use method that accepts exactly the same 
// number and type of parameters as in delegate EventHandler<TodoItem>  

list.ItemAdded += (eventhandler);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download