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?
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 object
s but are not inherently object
s.
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.
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