Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an item of type T to a List<T> without knowing what T is?

I'm handling an event which passes event args pointing to a List and a T newitem, and my job is to add the newitem to the List.

How can I do this without checking for all the types I know T might be?

The current code is a couple dozen lines of this:

private void DataGridCollectionViewSource_CommittingNewItem(object sender, DataGridCommittingNewItemEventArgs e)
{
  Type t = e.CollectionView.SourceCollection.GetType();

  if (t == typeof(List<Person>))
  {
    List<Person> source = e.CollectionView.SourceCollection as List<Person>;
    source.Add(e.Item as Person);
  }
  else if (t == typeof(List<Place>))
  {
    List<Place> source = e.CollectionView.SourceCollection as List<Place>;
    source.Add(e.Item as Place);
  }
  ...

I'd prefer if it were possible to do something like this:

((List<T>) e.CollectionView.SourceCollection).Add((T)e.Item);

Any ideas?

like image 739
Alain Avatar asked Feb 27 '12 16:02

Alain


3 Answers

Simply don't use generics here:

IList source = (IList)e.CollectionView.SourceCollection;
source.Add(e.Item);

You could also use ICollection in place of IList.

like image 64
Marc Gravell Avatar answered Nov 03 '22 05:11

Marc Gravell


Since generic collections implement object-based interfaces defined in the System.Collections namespace, you can do this:

((System.Collections.IList) e.CollectionView.SourceCollection).Add(e.Item);

Of course the type checking is now shifted to runtime, so you need to make sure that e.Item would be of the correct type, because the compiler cannot check it after the cast.

like image 37
Sergey Kalinichenko Avatar answered Nov 03 '22 05:11

Sergey Kalinichenko


You could make a specific typed class?

public class MyClass<ABC>
    {
        private void DataGridCollectionViewSource_CommittingNewItem(
              object sender, DataGridCommittingNewItemEventArgs e)
        {
            Type t = e.CollectionView.SourceCollection.GetType();

        if (t == typeof(List<ABC>))
        {
            List<ABC> source = e.CollectionView.SourceCollection as List<ABC>;
            source.Add(e.Item as ABC);
        }
    }
}

or not depending on the context of what your trying to do....

like image 27
AnthonyLambert Avatar answered Nov 03 '22 03:11

AnthonyLambert