Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass generic list into ObservableCollection constructor

I'm sure I'm missing something here, but any particular reason this doesn't work?

public ObservableCollection<object> ItemCollection { get; set; }

private void SetListData<T>(List<T> MyList)
{
    ItemCollection = new ObservableCollection<object>(MyList);
}

Is there some value for T where this won't work? I figure collection of objects would cover every case, but it seems not:

Error 2 Argument 1: cannot convert from 'System.Collections.Generic.List<T>' to 'System.Collections.Generic.List<object>'

Changing the signature of the property would cause a whole new set of problems, so changing it to:

ItemCollection = new ObservableCollection<T>(MyList);

doesn't seem like a good solution. Can anyone tell me why my original code doesn't work, and if there is any easy fix?

like image 370
Kevin DiTraglia Avatar asked Jun 19 '13 13:06

Kevin DiTraglia


1 Answers

You have a couple of options:

private void SetListData<T>(List<T> MyList) where T : class

or

ItemCollection = new ObservableCollection<object>(MyList.Cast<object>());

If you had a List<T> of a known reference type, it could work, even though the type parameter is not object:

var list = new List<string>();
var observable = new ObservableCollection<object>(list);

But in this case you are using the generic parameter, which is not a known reference type; it could be a value type/struct. These can be "boxed" as objects but are not inherently objects.

Thus, you must either constrain that parameter to always be a reference type, or allow any type T and do an explicit cast to object inside the body of the method.

like image 52
Jay Avatar answered Oct 13 '22 00:10

Jay