Search code examples
c#listilist

Passing List by ref when IList by ref is the method signature


I am having trouble with the code below. I want my method to take an IList, not a List But am I misguided?

Here is my method:

public void DoFoo( ref IList<Foo> thingy) {}

Here is the declaration and call:

var foo = new List<Foo>();
DoFoo( ref foo)

Why will this not compile? foo definitely implements IList If is because the compile will have to cast from List to IList ?


Solution

  • Type inference gets in the way here. The var is equivalent to declaring a List directly but you want an IList. You'll have to write the expected type explicitly in your declaration.

    IList<foo> foo = new List<Foo>();
    DoFoo( ref foo)