troubleshooting Question

Can't upcast List<MyType> to List<Object>

Avatar of josgood
josgoodFlag for United States of America asked on
C#
11 Comments1 Solution1107 ViewsLast Modified:
Have been away from C# for a while and have the feeling I've forgotten something essential.  The code below is a contrived example of my problem.

The SomeFunction call throws InvalidCastException, Message=Unable to cast object of type 'System.Collections.Generic.List`1[Test.MyType]' to type 'System.Collections.Generic.List`1[System.Object]'.

This should be an upcast -- I've tried deriving MyType from Object but that doesn't help -- and shouldn't be a problem.

What am I doing wrong?

using System;
using System.Collections.Generic;

namespace Test {

   public class MyType {
   }

   class Program {

      static void Main(string[] args) {
         List<MyType> aList = new List<MyType>();
         SomeFunction((List<Object>)(Object)aList);
      }

      static void SomeFunction(List<Object> parm) {
      }
   }
}
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 11 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 11 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros