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?
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
.
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.
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....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With