views:

70

answers:

1

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?

+1  A: 

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?

Donut
Actually my problem was that I was passing the object to a different project, which was not aware of the MyList class, and therefore it didn't know how to cast it. So now I am just casting MyList before sending it to the other project.
Out4345