I have following sample code in C# that is not behaving according to what I expect. My expectation is that a derived type is implicitly cast to less derived type, and this turns out be the case with array scenario code
but not with generic collections scenario code
.
Since a string type is implicitly cast to object type by C#, so the code below should work for both scenarios but it doesn't.
I am assigning an array or collection of strings to an array or collection of objects in code below.
Question: Why is the generic collection not behaving like an array in code below?
jsfiddle for this code is at C# code for this question
C# code
//arrays scenario
object[] objs = new object[3];
string[] strs = new string[] {"a","b","c"};
objs = strs;//THIS WORKS
//Generic collections scenario
List<object> objects = new List<object>();
List<string> strings = new List<string>{"a","b","c"};
objects = strings; //BUT this does not work