Recently I got a task to work on one of the FxCop warning - Do not expose generic lists. So I tried changing the List<T>
to ICollection<T>
. But later point of time, while doing the unit testing I found that the AddRange()
is not working properly as expected. It is not adding the collection of elements to the collection object.
Here is the sample code
gc.ToList().AddRange(sampleList);
And I have two questions to ask
Why it is not adding the items to the collection. Below is the code:
public class GenericClass { public int Id; public string Name; } class Program { static void Main(string[] args) { ICollection<GenericClass> gc = new List<GenericClass>(); var sampleList = new List<GenericClass>() { new GenericClass {Id = 1, Name = "ASD"}, new GenericClass {Id = 2, Name = "QWER"}, new GenericClass {Id = 3, Name = "BNMV"}, }; Console.WriteLine(gc.GetType()); // gc is of type gc.ToList().AddRange(sampleList); // sampleList items are not getting added to gc. Console.ReadKey(); }
}
List<T>
inherits fromICollection<T>
andList<T>
hasAddRange()
, etc functions. When I tried to cast to parent reference (ICollection<T>
) to child class object (List<T>
), why doesn't Intellisense suggestAddRange()
. Instead I need to do.ToList()
and then it showsAddRange()
.
I searched a lot for this. But couldn't find a reason that satisfied me. So please help me with the understanding. It will be a great help.