The class Countries
derives from List<Country>
, meaning it is more specific. You cannot assign a more general class to a reference intended for something more specific.
Countries countries = new List<Country>(); //Won't work
String s = new object(); //Won't work
You can assign specific to general, e.g.
List<Country> countries = new Countries(); //Will work
object o = ""; //Will work
If you have a List<Country>
and you need to convert it to a Countries
object, you can do so by implementing one of the constructors that allows you to populate the list, like this:
public class Country
{
public string Name { get; set; }
}
public class Countries : List<Country>
{
public Countries(IEnumerable<Country> initializationData) : base(initializationData)
{
//No body. Work is done by base class constructor.
}
}
Now you can:
List<Country> list = new List<Country>();
Countries countries = new Countries(list);
Note that this duplicates, not casts, the list, so you end up with two references to two distinct objects that contain the same data. This is the only way to do it.