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);
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
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments