In my Windows Store App I used c# 5.0. And I need to call the method which takes collection of base class, by passing collection of child class:
public class Foo // base class
{
public int fooVariable = 1;
public void fooMethod(){....};
}
public class Bar:Foo // child class
public void DoSomething(Foo foo)
public void DoSomething(List<Foo> foos)
{
foreach (var foo in foos)
{
Debug.WriteLine(foo.i); //access to variable
foo.fooMethod(); //access to method
foo.i = 10; //!!!i can change variable!!!
}
}
private List<Bar> _list;
public void Call()
{
DoSomething(new Bar()); // ok
_list = new List<Bar>();
list.Add(new Bar()); // I can add a lot of items.
DoSomething(list); // not ok
foreach (var foo in foos)
{
Debug.WriteLine(foo.i); // in console I need to see '10'
}
}
Is it possible to circumvent such limitation? If yes - how?
UPD
In DoSomething
I neeed full access to all public methods/variables(read/write) /properties(read/write)
It looks like DoSomething(List<Foo> foos)
only actually needs to iterate over the list. So you can change it to:
public void DoSomething(IEnumerable<Foo> foos)
{
// Body as before
}
Now you can pass in a List<Bar>
to that method due to the fact that IEnumerable<T>
is covariant in T
.
See more on this question at Stackoverflow