Question

I have a class similar to the following that uses an internal List:

public class MyList<T> : IEnumerable<T>
{
        private List<T> _lstInternal;
        public MyList()
        {
            _lstInternal = new List<T>();
        }
        public static implicit operator List<T>(MyList<T> toCast)
        {
            return toCast._lstInternal;
        }

}

When I try to pass MyList<object> to a function that takes a List<object>, I get an InvalidCastException. Why?

Was it helpful?

Solution

Using the class you described, the following code worked for me:

static void Main(string[] args)
{
   MyList<object> foo = new MyList<object>();

   MyMethod(foo);
}

static void MyMethod(List<object> things)
{
   // No InvalidCastException when called...
}

The only thing I changed from the MyList<T> class you posted in your question was adding the following implementation of IEnumerable<T>:

IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
    return _lstInternal.GetEnumerator();
}

IEnumerator IEnumerable.GetEnumerator()
{
    return _lstInternal.GetEnumerator();
}

Not really sure why you're getting an exception, except as I mentioned in my comment, I'm using C# version 4.0. What version are you using?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top