1

I created a Country profile

public class Country
{
   public string Name { get; set;}
}

and Countries list

public class Countries : List<Country>
{}

and now I want to assign List to Countries type variable

Countries countries = new List<Country>(new Country[] {new Country()});

but it unfortunately doesn't work. It says

can't convert List to Countries

what can the reason be? should I change List to something other?

Mureinik
  • 252,575
  • 45
  • 248
  • 283
Dakito
  • 171
  • 2
  • 7

3 Answers3

1

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.

John Wu
  • 44,075
  • 6
  • 37
  • 69
1

You can't implicitly cast list that.

You need to give your Countries class a constructor:

public class Countries : List<Country>
{
    public Countries(Country[] countries) : base(countries)
    {
    }
}

And then call it:

Countries countries = new Countries(new Country[] {new Country()});
Mureinik
  • 252,575
  • 45
  • 248
  • 283
1

I'm going to answer your question by simplifying your architecture. There is no reason to be inheriting from list. See this answer for more details If you want to encapsulate your logic for your country just have a property for the list of countries. Your model does not need to extend the functionality of a list.

public class Countries
{
    protected IEnumerable<Country> _countries;
    public Countries(IEnumerable<Country> countries)
    {
        this._countries = countries;
    }
}

Then you can initialize like so:

var countries = new Countries(new Country[] {new Country()});
johnny 5
  • 16,589
  • 46
  • 82
  • 156