Way I could not merge List and List? OOP says MyType2 is MyType…
using System;
using System.Collections.Generic;
namespace two_list_merge
{
public class MyType
{
private int _attr1 = 0;
public MyType(int i)
{
Attr1 = i;
}
public int Attr1
{
get { return _attr1; }
set { _attr1 = value; }
}
}
public class MyType2 : MyType
{
private int _attr2 = 0;
public MyType2(int i, int j)
: base(i)
{
Attr2 = j;
}
public int Attr2
{
get { return _attr2; }
set { _attr2 = value; }
}
}
class MainClass
{
public static void Main(string[] args)
{
int count = 5;
List<MyType> list1 = new List<MyType>();
for(int i = 0; i < count; i++)
{
list1[i] = new MyType(i);
}
List<MyType2> list2 = new List<MyType2>();
for(int i = 0; i < count; i++)
{
list1[i] = new MyType2(i, i*2);
}
list1.AddRange((List<MyType>)list2);
}
}
}
I’m going to assume that you’re not using C# 4.0.
In earlier versions of C#, this won’t work because the language doesn’t support contravariance and covariance of generic types.
Don’t worry about the academic jargon – they’re just the terms for the kinds of variance (i.e. variation) permitted.
Here’s a good article on the details:
http://blogs.msdn.com/b/csharpfaq/archive/2010/02/16/covariance-and-contravariance-faq.aspx
To make your code work, write this: