Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiler Error: Cannot convert from 'List<string>' to 'IList<object>'

How would I change the following code to make it compile? (Other than casting/changing strings to List<object>).

Action<IList<object>> DoSomething = (list) => { /*list is never modified*/ };
var strings = new List<string>() { "one", "two" };
DoSomething(strings);
like image 653
Lee Grissom Avatar asked Jan 20 '26 17:01

Lee Grissom


1 Answers

As the compiler error indicates, you can't cast a IList<string> to an IList<object>. This is because the IList<T> interface is invariant with respect to T. Imagine if your did something like this:

Action<IList<object>> DoSomething = (list) => list.Add(1);

This would be valid with a IList<object> but not with an IList<string>.

As long as you're not trying to modify the collection, a simple solution is to change the IList<T> to IEnumerable<T>, which is covariant with respect to T:

Action<IEnumerable<object>> DoSomething = (list) => { };
var strings = new List<string>() { "one", "two" };
DoSomething(strings);

Further Reading

  • Covariance and Contravariance in Generics
  • Covariance and contravariance (computer science)
like image 92
p.s.w.g Avatar answered Jan 23 '26 19:01

p.s.w.g



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!