Problem with list item type conversion

  • Thread starter Thread starter Tomasz Jastrzebski
  • Start date Start date
T

Tomasz Jastrzebski

Hello Developers,

I know it is a stupid question but why C# does not want to automatically
convert (up cast) list item types as it does with arrays? (example below)

I would like to be able to pass lists of MyBaseClass derived classes to
MyFunction. Do I need to implement some conversion? Somehow I never came
across this problem.

Thanks for any pointers.

Thomas


class Program
{
static void Main(string[] args)
{
List<MyDerivedClass> list = new List<MyDerivedClass>();

MyFunction(list);
}

static void MyFunction(List<MyBaseClass> list)
{
}
}

class MyBaseClass { }
class MyDerivedClass : MyBaseClass { }
 
Hello Developers,

I know it is a stupid question but why C# does not want to automatically
convert (up cast) list item types as it does with arrays? (example below)

Because if it let you do that, then you could later add something to your
list that isn't of type "MyDerivedClass".

Google for "C# generic covariance" for more details. The C# 4.0 version
has a new feature that supports _related_ operations (for example, you'll
be able to get an IEnumerable<MyBaseClass> from your
List<MyDerivedClass>), but the specific thing you're trying to do will
never work, because it's not safe for it to work.

Assuming you're currently stuck with the released version of VS, you
should look at the Enumerable.Cast() extension method or just create a new
List<MyBaseClass> using the appropriate constructor (to pass your existing
List<MyDerivedClass> as the initializer), depending on your specific needs.

Pete
 
Thanks Pete. I see that the problem as stated cannot be solved. Fortunately,
it can be circumvented - see below.

Thomas


class Program
{
static void Main(string[] args)
{
List<MyDerivedClass> list = new List<MyDerivedClass>();

MyFunction(list);
}

static void MyFunction<T>(List<T> list)
where T : MyBaseClass
{
}
}

class MyBaseClass { }
class MyDerivedClass : MyBaseClass { }
 
Back
Top