0

Take the following example :

     public interface IModel
    {
        public string FirstPropery { get; set; }
    }

    public class Model : IModel
    {
        public string FirstPropery { get; set; }
    }

    public List<Model> GetActualModels() 
    {
        var models = new List<Model>();

        models.Add(new Model
        {
            FirstPropery = "1"
        });

        models.Add(new Model
        {
            FirstPropery = "2"
        });

        return models;
    }


     public List<IModel> GetModels()
     {
        return GetActualModels();
     }

This does not compile, we have an error on GetModels()

"Error  CS0029  Cannot implicitly convert type 'System.Collections.Generic.List<ConsoleApp1.Model>' to 'System.Collections.Generic.List<ConsoleApp1.IModel>'"

Then if we change the function just a bit to :

 public List<IModel> GetModels()
 {
    var models = GetActualModels();

    var modelsInterface = new List<IModel>();

    modelsInterface.AddRange(models);

    return modelsInterface;
 }

This does not throw any compiling error. It must be a question answered many times but I have no idea how to search for the answer to it. Any ideas why this strange behaviour?

CiucaS
  • 2,010
  • 5
  • 36
  • 63

1 Answers1

1

You can change your function a bit to Cast every element in your list like this:

public static List<IModel> GetModels()
{
    return GetActualModels().Cast<IModel>().ToList();
}

From the documentation

Casts the elements of an IEnumerable to the specified type.

ravi kumar
  • 1,548
  • 1
  • 13
  • 47