The reason it doesn't compile is that the ref
allows the method to do this:
public void DoFoo( ref IList<Foo> thingy)
{
thingy = new Foo[10];
}
Arrays implement IList<T>
, but they're not List<T>
, and that's why the compiler refuses to compile the code.
You have a parameter that refers to a variable of a specific type, in this case List<Foo>
, and you can't stuff other types of collections in there, unless they inherit from List<Foo>
.
There is one way to circumvent this, just copy the list to a variable of the right type, but you also need to decide what happens if the method actually replaces the contents of that variable.
In other words, you can do this:
IList<Foo> il = foo;
DoFoo(ref il);
// what if il is a new reference here now?
As already mentioned in another answer, objects (and thus lists in this case) are already references. Are you sure you need the ref
in the first place? Let me clarify. Objects in .NET are reference types, which means you pass a reference to the object. Using a ref
parameter allows you to pass a parameter by reference, which is different.
Passing a reference allows the method to access the same object as the outside world. Passing by reference allows the method to access the variable in the outside world.
ref
there in the first place? – PyramidalIList<T>
, the latter isref IList<T>
; they are very different. – Kutchpublic IList<Foo> DoFoo( IList<Foo> thingy) {}
and then useIList<Foo> foo = new List<Foo>();foo = DoFoo(foo);
. Still ugly, though. – Massage