I’m still learning some of this c# stuff, and I couldn’t find an answer to this question. Assuming that I have a list of MyObject implementing MyInterface
public class MyObject : IMyInterface { ...}
public List<MyObject> MyObjectList;
How can I return an IEnumerable<IMyInterface> with the contents of MyObjectList?
I mean, right now I have this:
List<IMyInterface> temp = new List<IMyInterface>();
foreach (MyObject obj in MyObjects) temp.Add(obj);
return (IEnumerable<IMyInterface>)temp;
But is it necessary to create a new list like this?
Thank you.
If you’re using .NET 3.5, the easiest way to do this is:
You don’t need to create a copy of everything – but until C# 4 comes out with its generic interface variance, you’re stuck doing something like this.
If you’re still using .NET 2.0, you can easily do something similar:
(Note that this doesn’t check for
sourcebeing null; to do that properly you’d want two methods due to the deferred execution of iterator blocks.)Then use:
You could make it more like the LINQ version, like this:
This has compile-time safety though – it wouldn’t stop you from trying to convert a
List<string>into anIEnumerable<Guid>for example.