Reputation: 91
Consider following method
public ICollection<int> method()
{
ICollection<int> col = new List<int>();
return col;
}
HashSet<int> result = (HashSet<int>) method();
Of course I'm getting error "Unable to cast object of type List to HashSet", because I've instantiaded col with List in method()
Is it possible to have generic method, which return ICollection and can be casted at HashSet or List, depending on my needs?
Upvotes: 0
Views: 3007
Reputation: 4166
No, you can't straight cast it because the instance returned is not a HashSet
or anything but a List
, but you can easily use the ICollection
instance returned to initialize a new instance of whatever you need. For example:
ICollection<int> result = Method();
HashSet<int> newHashSet = new HashSet<int>(result);
Upvotes: 2