I have the following code
class Program { static void Main(string[] args) { List<A> aList = new List<A>(); var aObj = new A(); aObj.Go(aList.Cast<IB>()); } } class A : IB { public void Go(IEnumerable<IB> interfaceList) { foreach (IB ibby in interfaceList) { Console.WriteLine('Here'); } } } interface IB { void Go(IEnumerable<IB> interfaceList); }
}
I originally tried passing a List but that doesn’t work. After a lot of help from SO I found that passing IEnumerable is the only way to get the objects across as .ofType(IB).
Unfortunately for me, in my code the following line will be executed thousands of times:
aList.Cast<IB>();
I was wondering if anyone knew how it was implemented algorithmically (in IL) and what its time order is.
That is to say, is it faster than a foreach loop that just casts each item, or is that exactly what it does?
EDIT The main class needs to maintain a list of the actual objects. But the reader is only allowed to touch them through the interface.
You should change
Goto:Then you’ll be fine with no need to call
Cast. I suspect the source code implementation of Cast is pretty simple, although I believe it changed between 3.5 and 3.5SP1. However, it probably needs to set up a new state machine etc in the normal iterator block fashion. Better to avoid it if possible.Even though the new method is generic, type inference should usually take care of it for you so you don’t need to specify
Texplicitly.