I'm just learning events in C# and was given the following example in a tutorial. My question is how I can display the contents of the string added/removed in my event handler.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SubscribeTest
{
class Program
{
static void Main(string[] args)
{
var coll = new ObservableCollection<string>();
// TODO: subscribe to an event here
coll.CollectionChanged += coll_CollectionChanged;
coll.Add("Big Mac");
coll.Add("Filet 'O Fish");
coll.Add("Quarter Pounder");
coll.Add("French Fries");
coll.Remove("Filet 'O Fish");
Console.ReadKey(true);
}
static void coll_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
//Does not do what I want it to.
Console.WriteLine(Convert.ToString(e.NewItems));
}
}
}
The Observable Collection, The Collection Changed and The Event Args documentation are pretty straight forward.
In the changed event you have the properties
NewItemsandOldItems(among others) that contain the newly added or removed objects from the collection. Now these are a simpleIList(not to be confused withIList<T>) so you have to do some casting. As we know the collection is a string we would expect theNewItemsor theOldItemscollection to contain string values.Now these properties are
nullif they are not applicable. ie. In aAddmethod (or action) theOldItemsproperty will be null. Therefore if you just want to print the changes try below.Full Changed Code: Again this doesnt worry about the action just prints the results.