0

Assigning child object to the base is possible.

base1 b1 = new child1();

But if we do the same with the collection it is not possible, Why?

List<base1> libase = new List<child1>();

Any reference having this explanation is very helpful, please share

        public class base1
        {

        }
        public class child1 : base1
        {

        }
        static void Main(string[] args)
        {
            base1 b1 = new child1();
            List<base1> libase = new List<child1>();
            Console.Read();   
        }
Amit Bisht
  • 4,870
  • 14
  • 54
  • 83

1 Answers1

1

In c# you can do such trick:

List<base1> libase = new List<base1>(new List<child1>());

Also, you can use Interface IEnumerable:

IEnumerable<base1> libase = new List<child1>();

Because it's declared as:

  public interface IEnumerable<out T> : IEnumerable
  {
    IEnumerator<T> GetEnumerator();
  }

out T it the most important.

When List is just:

public class List<T>
{}

About your question read more here Covariance and Contravariance in Generics

Backs
  • 24,430
  • 5
  • 58
  • 85