[C#] Using CopyTo with lists and interfaces. Can't convert to interface type?

Started by
4 comments, last by Nikster 12 years, 9 months ago
I have an interface:



interface IFoo
{
bool IsTasty { get; set; }
}


and a class that inherits from it:



class Bar : IFoo
{
private bool isTasty;

public Bar() { }

public bool IsTasty
{
get { return isTasty; }
set { isTasty = value; }
}
}


When I create a list of Bars:



List<Bar> bars = new List<Bar>();
bars.Add(new Bar());


which I wish to store inside an Array of the interface IFoo:


IFoo[] foos = new IFoo[12];


I can do the following:


foos[0] = bars[0];


but if I try and use the 'CopyTo' method, the type conversion fails:


bars.CopyTo(foos, 0);




Argument 1: cannot convert from 'Prototype1.IFoo[]' to 'Prototype1.Bar[]'
[/quote]

How can I get this to work correctly?
Advertisement
I dare say a C# guru can do it better, but you could do this:

Array.Copy(bars.ToArray<IFoo>(), foos, Math.Min(bars.Count, foos.Length));

Obviously if you don't mind losing the foo array then you could just overwrite it rather than copy into it...

foos = bars.ToArray<IFoo>();
I thought about using the 'ToArray' method but wasn't sure if it would fare better than iterating over the list and copying them across that way. That way some garbage collection would be avoided.
I know it doesn't answer your question, but is there any reason you don't just use an List<IFoo>? Or are you wanting to keep a list of derived types then concatenate them later.?

[color=#1C2837][size=2]Or are you wanting to keep a list of derived types then concatenate them later.?
[color=#1C2837][size=2][/quote]
[color=#1C2837][size=2]

[color="#1c2837"]That's correct. I have a system where all transparent objects are concatenated into an array of IDrawableTransparent(s). I then project their positions onto the camera's forward and sort them by distance so they can be drawn in the correct order.
Ok, so it doesn't work because you're essentially doing ICollection<Bar>.CopyTo( Bar[] array, ...) so you can either have List<IFoo> instead of List<Bar>, convert to a new array as already suggested or you can take the opportunity to have your own sort in place which may(not) turn out to be the best / fast approach for your implimentation.

What you could do with is a CopyFrom() ;)

This topic is closed to new replies.

Advertisement