C #: No castings in Generics?

While I can raise a string to an object, I cannot convert IList strings to IList objects. How so? What to do now to others who cope with all subjects in the new IList?

static void ThisWorks()
{
     IList<object> list = new List<object>();
     list.Add("I can add a string since string : object");
}

static void ThisDoesNotWork()
{
     // throws an invalid cast exception
     IList<object> list = (IList<object>) new List<string>(); 

     list.Add("I'm never getting here ... why?");
}
+3
source share
4 answers

Look at it this way: while a banana is a fruit, a banana basket is not a fruit basket, as you can add oranges to the last, but not to the first. Yours List<string>has more severe limitations than List<object>.

Liskow. , , , , .

+4

, generics ( # 3.0).

:

var objectList = list.Cast<object>().ToList();
+7

, , , . , , . , .

+4

string object, IList<string> IList<object>, , .

, , :

// THIS CODE DOES NOT WORK
IList<object> list = new List<string>(); // this doesn't compile
list.Add(5); // because this is perfectly valid on IList<object> but not on IList<string>
+1

Source: https://habr.com/ru/post/1706670/


All Articles