Casting an object to a IList with an abstract type parameter

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


Casting an object to a IList with an abstract type parameter



In my code, I have an object:


object obj = ...



Which I know is of type MyListType, where MyListType is a subclass of IList and T is a subclass of MyAbstractClass. The type parameter of MyListType is constrained so that it is always a subclass of MyAbstractClass.



However, trying to cast obj


MyListType<MyAbstractClass> myList = (MyListType<MyAbstractClass>)obj;



gives a runtime error.



I tried to define an explicit operator


public static explicit operator MyListType<MyAbstractClass>(MyListType<T> list)
{
MyListType<MyAbstractClass> newList = new MyListType<MyAbstractClass>();
foreach(T t in list)
newList.Add((MyAbstractClass) t);
return newList;
}



However, this operator doesn't get used by the cast since obj is an object, not a MyListType. Is there a workaround to successfully perform this cast?



I've looked at this question, but their the list was of an unknown type.









By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Makefile test if variable is not empty

Will Oldham

Visual Studio Code: How to configure includePath for better IntelliSense results