views:

6352

answers:

40

In c#/VB.NET/.NET which loop runs faster for or foreach?

Ever since I read that for loop works faster than foreach a long time ago I assumed it stood true for all collections, generic collection all arrays etc.

I scoured google and found few articles but most of them are inconclusive (read comments on the articles) and open ended.

What would be ideal is to have each scenarios listed and the best solution for the same

e.g: (just example of how it should be)

  1. for iterating an array of 1000+ strings - for is better than foreach
  2. for iterating over IList (non generic) strings - foreach is better than for

Few references found on the web for the same:

  1. Original grand old article by Emmanuel Schanzer
  2. CodeProject FOREACH Vs. FOR
  3. Blog - To foreach or not to foreach that is the question
  4. asp.net forum - NET 1.1 C# for vs foreach

[Edit]
Apart from the readability aspect of it I am really interested in facts and figures, there are applications where the last mile of performance optimization squeezed do matter.

+19  A: 

My guess is that it will probably not be significant in 99% of the cases, so why would you choose the faster instead of the most appropriate (as in easiest to understand/maintain)?

Brian Rasmussen
I totally agree with you.
Leandro López
Right, but you should care in 1% of cases :). But these %'s depends on what kind of work you are doing. I, in most cases, am writing programs for physics simulation and I'd say that about 20% of my loops should work as fast as it is possible. Yet, I'm not using C# for it.
klew
@klew, If you actually profile your code you wouldn't have to guess which 20% need to be as fast as possible. You would probably also find out that the actual number of loops which need to be fast is much lower. Furthermore, are you really saying that the act of looping is where you spend your time, as opposed to what you actually do in that loop?
tster
+19  A: 

It will always be close. For an array, sometimes for is slightly quicker, but foreach is more expressive, and offers LINQ etc. In generral, stick with foreach.

Additionally, foreach may be optimised in some scenarios. For example, a linked list might be terrible by indexer, but might be quick by foreach. Actually, the standard LinkedList<T> doesn't even offer an indexer for this reason.

Marc Gravell
+1 for mentioning cases other than array and List<T> where 'foreach' can be faster
Lucas
So are you saying `LinkedList<T>` is leaner than `List<T>`? And if I'm always going to be using `foreach` (instead of `for`), I'm better off using `LinkedList<T>`?
JohnB
@JohnB - not leaner; just different. For example, each node in a linked list has additional references that aren't needed for a flat array (which also underpins `List<T>`). It is more that it is cheaper to *insert* / *remove*.
Marc Gravell
+1  A: 

I did it test a time ago, with the result that a for-loop is much faster, than a foreach-loop. Cause is simple, the foreach-loop needs to instantiate an IEnumerator for the collection first.

BeowulfOF
Not with an array it doesn't. Compile it and look at the IL :) (It also depends on the collection. IIRC, List<T> uses a value type for the enumerator.)
Jon Skeet
Why would one allocation be expensive? In managed .NET, allocations are practically free aren't they, since all that is done is that the pointer is incremented in the managed heap, there is little if any fragmentation in most cases.
ApplePieIsGood
not just one allocation, also all the method-calling overhead of MoveNext() and get_Current() for each iteration.
Lucas
+1  A: 

for has more simple logic to implement so it's faster than foreach.

Braveyard
What ? What did they give me thumbs down ?
Braveyard
i have no idea, i thumb you up :)
Itay
@Italy : Thanks for your concern :)
Braveyard
+9  A: 

Premature optimization is the root of all evil.

Use whichever better expresses your intent first; if it's profiled to be a bottle-neck (which I'm going to doubt), then test the other way.

Andrew Coleson
But premature optimization happens after you already wrote the code, not before.
Joan Venge
+37  A: 

Patrick Smacchia blogged about this last month, with the following conclusions:

  • for loops on List are a bit more than 2 times cheaper than foreach loops on List.
  • Looping on array is around 2 times cheaper than looping on List.
  • As a consequence, looping on array using for is 5 times cheaper than looping on List using foreach (which I believe, is what we all do).
Ian Nelson
+1 Great article.However, never forget: "Premature optimization is the root of all evil."
Oorang
Yeah so instead of taking .005 seconds to loop through your list it could take .001 seconds to loop through an array. Glad I spent all day looking up which one was faster.
Hardwareguy
@Hardwareguy: Once you know that for is almost imperceptably faster, why shouldn't you start using it in general? It doesn't take extra time.
XD am I the only one to find here a logical failure? and +1 to devinb comment here
Itay
@devinb, using "for" is harder than using "foreach" as it adds code, another variable, a condition you need to check, etc. How many times have you seen an off-by-one error in a "foreach" loop?
tster
lol I haven't seen an off by one error in a for loop since freshman year of college.
Neil N
@Hardwareguy, let me see if I got this straight. It takes 5 times longer to loop through a list with `foreach` than it does to loop through an array with `for`, and you're calling that insignificant? That kind of a performance difference might matter for your application, and it might not, but I wouldn't just dismiss it out of hand.
Robert Harvey
Reading through the blog post it looks like the tests were run in Debug and not Release so that might have a factor. Additionally the difference is specifically for just the loop overhead. It doesn't affect the time to execute the body of the loop at all which is most cases is much longer than the time it takes to move to the next element of the list. It's good information to know when you've identified that there clearly is a problem and you've measured the difference in your app specifically and there's a noticeable improvement but definitely not general advice to remove all `foreach`s.
Davy8
+4  A: 

The differences in speed in a for- and a foreach-loop are tiny when you're looping through common structures like arrays, lists, etc, and doing a LINQ query over the collection is almost always slightly slower, although it's nicer to write! As the other posters said, go for expressiveness rather than a millisecond of extra performance.

What hasn't been said so far is that when a foreach loop is compiled, it is optimised by the compiler based on the collection it is iterating over. That means that when you're not sure which loop to use, you should use the foreach loop - it will generate the best loop for you when it gets compiled. It's more readable too.

Another key advantage with the foreach loop is that if your collection implementation changes (from an int array to a List<int> for example) then your foreach loop won't require any code changes:

foreach (int i in myCollection)

The above is the same no matter what type your collection is, whereas in your for loop, the following will not build if you changed myCollection from an array to a List:

for (int i = 0; i < myCollection.Length, i++)
Alex York
+4  A: 

It probably depends on the type of collection you are enumerating and the implementation of it's indexer. In general though, using foreach is likely to be a better approach.

Also, it'll work with any IEnumerable - not just things with indexers.

Andrew Kennan
+21  A: 

There is unlikely to be a huge performance difference between the two. As always, when faced with a "which is faster?" question, you should always think "I can measure this."

Write two loops that do the same thing in the body of the loop, execute and time them both, and see what the difference in speed is. Do this with both an almost-empty body, and a loop body similar to what you'll actually be doing. Also try it with the collection type that you're using, because different types of collections can have different performance characteristics.

Greg Hewgill
+36  A: 

First, a counter-claim to Dmitry's answer. For arrays, the C# compiler emits largely the same code for foreach as it would for an equivalent for loop. That explains why for this benchmark, the results are basically the same:

using System;
using System.Diagnostics;
using System.Linq;

class Test
{
    const int Size = 1000000;
    const int Iterations = 10000;

    static void Main()
    {
        double[] data = new double[Size];
        Random rng = new Random();
        for (int i=0; i < data.Length; i++)
        {
            data[i] = rng.NextDouble();
        }

        double correctSum = data.Sum();

        Stopwatch sw = Stopwatch.StartNew();
        for (int i=0; i < Iterations; i++)
        {
            double sum = 0;
            for (int j=0; j < data.Length; j++)
            {
                sum += data[j];
            }
            if (Math.Abs(sum-correctSum) > 0.1)
            {
                Console.WriteLine("Summation failed");
                return;
            }
        }
        sw.Stop();
        Console.WriteLine("For loop: {0}", sw.ElapsedMilliseconds);

        sw = Stopwatch.StartNew();
        for (int i=0; i < Iterations; i++)
        {
            double sum = 0;
            foreach (double d in data)
            {
                sum += d;
            }
            if (Math.Abs(sum-correctSum) > 0.1)
            {
                Console.WriteLine("Summation failed");
                return;
            }
        }
        sw.Stop();
        Console.WriteLine("Foreach loop: {0}", sw.ElapsedMilliseconds);
    }
}

Results:

For loop: 16638
Foreach loop: 16529

Next, validation that Greg's point about the collection type being important - change the array to a List<double> in the above, and you get radically different results. Not only is it significantly slower in general, but foreach becomes significantly slower than accessing by index. Having said that, I would still almost always prefer foreach to a for loop where it makes the code simpler - because readability is almost always important, whereas micro-optimisation rarely is.

Jon Skeet
"change the array to a List<double> in the above, and you get radically different results" Very interesting, I hadn't thought about that
johnc
Given the strange differences in results between my tests and other people's benchmarks, I think this is going to merit a blog post...
Jon Skeet
Which do you *almost always* prefer between arrays and `List<T>`? Does readability trump micro-optimization in that case too?
JohnB
@JohnB: Yup - I almost always prefer `List<T>` over arrays. The exceptions are `char[]` and `byte[]` which are more often treated as "chunks" of data rather than normal collections.
Jon Skeet
+1  A: 

See this answer for a specific benchmark.

David Schmitt
That's very *very* interesting - because it gives entirely different results than my benchmark. Hmm. Will investigate.
Jon Skeet
+1  A: 

I would suggest reading this for a specific answer. The conclusion of the article is that using for loop is generally better and faster than the foreach loop.

Rekreativc
That conclusion was written in 2004. Things have moved on. See my benchmark.
Jon Skeet
+1  A: 

Unless you're in a specific speed optimization process, I would say use whichever method produces the easiest to read and maintain code.

If an iterator is already setup, like with one of the collection classes, then the foreach is a good easy option. And if it's an integer range you're iterating, then for is probably cleaner.

GeekyMonkey
+5  A: 

To quote Micheal A. Jackson

What is the first rule of optimisation?

Answer - Don't do it

What is the second rule of optimisation?

Answer - Don't do it Yet (For experts only).

And according to Donald Knuth "premature optimization is the root of all evil"

Always profile your application not some micro-benchmark.

What's the point of fixing a few milliseconds here and there when you've got seconds wasted elsewhere.

+1  A: 

Jeffrey Richter talked the performance difference between for and foreach on a recent podcast: http://pixel8.infragistics.com/shows/everything.aspx#Episode:9317

Chuck Conway
A: 

I wouldn't expect anyone to find a "huge" performance difference between the two.

I guess the answer depends on the whether the collection you are trying to access has a faster indexer access implementation or a faster IEnumerator access implementation. Since IEnumerator often uses the indexer and just holds a copy of the current index position, I would expect enumerator access to be at least as slow or slower than direct index access, but not by much.

Of course this answer doesn't account for any optimizations the compiler may implement.

JohannesH
The C# compiler does very little optimisation, it really leaves that up to the JITter.
kronoz
Well, the JITter is a compiler... Right?
JohannesH
A: 

Keep in mind that the for-loop and foreach-loop are not always equivalent. List enumerators will throw an exception if the list changes, but you won't always get that warning with a normal for loop. You might even get a different exception if the list changes at just the wrong time.

Strilanc
A: 

In general for would be faster then foreach. However if you care you've probably got "other problems" which are of higher importance...

Thomas Hansen
+3  A: 

Jeffrey Richter on TechEd 2005:

"I have come to learn over the years the C# compiler is basically a liar to me." .. "It lies about many things." .. "Like when you do a foreach loop..." .. "...that is one little line of code that you write, but what the C# compiler spits out in order to do that it's phenomenal. It puts out a try/finally block in there, inside the finally block it casts your variable to an IDisposable interface, and if the cast suceeds it calls the Dispose method on it, inside the loop it calls the Current property and the MoveNext method repeatedly inside the loop, objects are being created underneath the covers. A lot of people use foreach because it's very easy coding, very easy to do.." .. "foreach is not very good in terms of performance, if you iterated over a collection instead by using square bracket notation, just doing index, that's just much faster, and it doesn't create any objects on the heap..."

On-Demand Webcast: http://msevents.microsoft.com/CUI/WebCastEventDetails.aspx?EventID=1032292286&amp;EventCategory=3&amp;culture=en-US&amp;CountryCode=US

Max Toro
Nice one, good to see Jeff being so explicit about this.
Binoj Antony
+47  A: 

foreach loops demonstrate more specific intent than for loops.

Using a foreach loop demonstrates to anyone using your code that you are planning to do something to each member of a collection irrespective of its place in the collection. It also shows you aren't modifying the original collection (and throws an exception if you try to).

The other advantage of foreach is that it works on any IEnumerable, where as for only makes sense for IList, where each element actually has an index.

However, if you need to use the index of an element, then of course you should be allowed to use a for loop. But if you don't need to use an index, having one is just cluttering your code.

There are no significant performance implications as far as I'm aware. At some stage in the future it might be easier to adapt code using foreach to run on multiple cores, but that's not something to worry about right now.

ctford
This is very helpful when iterating through a custom object list or datalist and not have to worry about all the index nomenclature when processing the data.
Dillie-O
+1 for -very- interesting comment about foreach running on multiple cores.Never thought of that, and interesting point to make.
Aequitarum Custos
I can't see how `foreach` helps multithreading. I guess you are referring to things like Task Parallel Library but that's not really a magic of `foreach`.
Mehrdad Afshari
@Mehrdad The compiler has freedom on how to iterate through the list with foreach. For example, it could iterate through the the even elements on one core and the odd elements on another.foreach is closer to the functional style of programming.
ctford
ctford: No it's not. The compiler certainly cannot reorder elements in `foreach`. `foreach` is not at all related to functional programming. It's **totally** an imperative paradigm of programming. You are mis-attributing things happening in TPL and PLINQ to `foreach`.
Mehrdad Afshari
@Mehrdad,ctford: I guess it depends if foreach has a guarantee of order. If foreach has no guarantee of order it could be optimized by a future version of the compiler to use the cores if there is something like an attribute to mark the code within the foreach loop as thread-safe ?
BlueTrin
@BlueTrin: It certainly does guarantee ordering (C# spec section 8.8.4 formally defines `foreach` as an equivalent of a `while` loop). I think I know @ctford is referring to. Task parallel library allows **the underlying collection** to provide elements in an arbitrary order (by calling `.AsParallel` on an enumerable). `foreach` doesn't do anything here and the body of the loop is executed on a **single thread**. The only thing that is parallelized is the generation of the sequence.
Mehrdad Afshari
@Mehrdad: Also, using foreach helps to avoid coupling your element processing code with any concept of ordering, thus making it more easily paralisable in the future. I overstated my point - foreach is not map.
ctford
`foreach` actually works with any IEnumerable-"like" object (not a correction to your post as much as an interesting note about duck typing): http://blogs.msdn.com/kcwalina/archive/2007/07/18/DuckNotation.aspx
280Z28
Enumerable.Select has an overload that lets you obtain the index of the item, so even the need for an index does not mandate using for. See http://msdn.microsoft.com/en-us/library/bb534869.aspx
TrueWill
+5  A: 

Yes you should be pissed. This is ridiculous.

In cases where you work with a collection of objects, foreach is better, but if you increment a number, a for loop is better.

Note that in the last case, you could do something like:

foreach (int i in Enumerable.Range(1,10))...

But it certainly doesn't perform better, it actually has worse performance compared to a for.

Meta-Knight
+2  A: 

Well, you seem to already know the answer, but if you need reassurance: yes you are right, the decision of your boss is ridiculous.

Andreas Bonini
+4  A: 

The two will run almost exactly the same way. Write some code to use both, then show him the IL. It should show comparable computations, meaning no difference in performance.

ck
Do you really think that a boss who forbids for loops would understand the IL? And would change his mind based on it?
Aric TenEyck
The compiler recognises foreach loops used on arrays/ILists etc and changes them to for loops.
Callum Rogers
Show him lines of unintelligble *proof* that it is OK and ask for his proof that it is not OK.
ck
+26  A: 

Any time there's arguments over performance, you just need to write a small test so that you can use quantitative results to support your case.

Use the StopWatch class and repeat something a few million times, for accuracy. (This might be hard without a for loop):

StopWatch sw = new StopWatch()
sw.Start()
for(int i = 0; i < 1000000;i ++)
{
    //do whatever it is you need to time
}
sw.Stop();
//print out sw.ElapsedMilliseconds

Fingers crossed the results of this show that the difference is negligible, and you might as well just do whatever results in the most maintainable code

Rob Fonseca-Ensor
Yes! End of a DISCUSSION!
Hamish Grubijan
But you can't compare performance of for and foreach. They are supposed to be used in different circumstances.
Michael Krelin - hacker
I agree with you Michael, you shouldn't choose which one to use based on performance - you should choose the one that makes the most sense! But if your boss says "Don't use for because it's slower than foreach" then this is the only way to convince him that the difference is negligible
Rob Fonseca-Ensor
"(This might be hard without a for loop)" Or you can use a while loop.
jonescb
+2  A: 

Either you're joking (hopefully), or you need to find a new job!

RichardOD
+7  A: 

This is ridiculous. There's no compelling reason to ban the for-loop, performance-wise or other.

See Jon Skeet's blog for a performance benchmark and other arguments.

Rik
+1 for the performance benchmarks. Evidence speaks.
Robert Harvey
A: 

Atleast I haven't seens any of my collegues or higher ups saying that, thats just ridiculous considering the fact that there is no significant speed difference between for and foreach, that too If he is asking to use it in all cases!

Mahesh Velaga
+1  A: 

It seems a bit strange to totally forbid the use of something like a for loop.

There's an interesting article here that covers a lot of the performance differences between the two loops.

I would say personally I find foreach a bit more readable over for loops but you should use the best for the job at hand and not have to write extra long code to include a foreach loop if a for loop is more appropriate.

colethecoder
Essential quote form the article you link to: "...if you are planning to write high performance code that is not for collections, use for loop. Even for collections, foreach may look handy when using, but it's not that efficient. "
NickFitz
+2  A: 

In most cases there's really no difference.

Typically you always have to use foreach when you don't have an explicit numerical index, and you always have to use for when you don't actually have an iterable collection (e.g. iterating over a two-dimensional array grid in an upper triangle). There are some cases where you have a choice.

One could argue that for loops can be a little more difficult to maintain if magic numbers start to appear in the code. You should be right to be annoyed at not being able to use a for loop and have to build a collection or use a lambda to build a subcollection instead just because for loops have been banned.

Cade Roux
+20  A: 

There are very good reasons to prefer foreach loops over for loops. If you can use a foreach loop, your boss is right that you should.

However, not every iteration is simply going through a list in order one by one. If he is forbidding for, yes that is wrong.

If I were you, what I would do is turn all of your natural for loops into recursion. That'd teach him, and its also a good mental exercise for you.


IMPORTANT NOTE:

For some weird reason, this question got merged yesterday with an almost completely unrelated question. If some of the answers in here (prime example: This one) don't seem to address the question at all, that is why.

The unrelated original question was about if it was ever a good idea to totally ban for loops, and what to do if you work where that was done.

T.E.D.
ha ha I'm going to start doing that!
Chuck Conway
How does recursion compare to `for` loops and `foreach` loops performance-wise?
JohnB
It depends. If you use tail-recursion and your compiler is smart enough to notice, it can be identical. OTOH: If it doesn't and you do something stupid like pass a lot of unnessecary (unchanging) data as parameters or declare big structures on the stack as locals, it can be really really slow (or even run out of RAM).
T.E.D.
Ahhh. I see why you asked that now. This answer went to a totally different question. For some bizzare reason Jonathan Sampson merged the two yesterday. He really shouldn't have done that. The merged answers will make no sense here whatsoever.
T.E.D.
+3  A: 

Whether for is faster than foreach is really besides the point. I seriously doubt that choosing one over the other will make a significant impact on your performance.

The best way to optimize your application is through profiling of the actual code. That will pinpoint the methods that account for the most work/time. Optimize those first. If performance is still not acceptable, repeat the procedure.

As a general rule I would recommend to stay away from micro optimizations as they will rarely yield any significant gains. Only exception is when optimizing identified hot paths (i.e. if your profiling identifies a few highly used methods, it may make sense to optimize these extensively).

Brian Rasmussen
If the only kind of optimization I needed to do in the projects I work on were micro optimizations, I would a happy camper. Sadly, this is never the case.
Yannick M.
`for` is marginally faster than `foreach`. I'd seriously object to this statement. That totally depends on the underlying collection. If a linked list class provides an indexer with an integer parameter, I would expect using a `for` loop on it to be O(n^2) while `foreach` is expected to be O(n).
Mehrdad Afshari
@Merhdad: Actually that is a good point. I was just thinking about the regular case of indexing a list (i.e. array). I'll reword to reflect that. Thanks.
Brian Rasmussen
@Mehrdad Afshari: Indexing a collection by integer may be *much* slower than enumerating over it. But you are actually comparing using `for` **and** an indexer lookup to using `foreach` by itself. I think @Brian Rasmussen's answer is correct that, aside from any use with a collection, `for` will always be slightly faster than `foreach`. However, `for` plus a collection lookup will always be slower than `foreach` by itself.
Daniel Pryden
@Daniel: Either you have a plain array, for which both will generate identical code, or there's an indexer involved when you use `for` statement. Plain `for` loop with an integer control variable is not comparable to `foreach`, so that's out. I understand what @Brian means and it's correct as you say but the answer can be misleading. Re: your last point: no, actually, `for` over `List<T>` is still faster than `foreach`.
Mehrdad Afshari
@Mehrdad- Surely with a LinkedList you'd write something like for(var node= list.Head; node != null; node = node.Next) if you wanted to use a for loop, making it O(n).
RichardOD
@RichardOD: The linked list class I was imagining abstracts away the nodes from you and you can either access items with a number, or with `foreach` ;) Anyway, my point is, strictly speaking, without knowing the underlying collection and the way it works, you can't say one is faster than another. It's like saying method `A()` is faster than `B()` without having an idea what they are doing.
Mehrdad Afshari
I think the only time one would reasonably use `for` on a linked list in .NET is for iterating over just a portion of the collection, so `foreach` would be inappropriate. But a case can be made that `while` is clearer in that case.
James M.
+11  A: 

It's time to link your account with careers.stackoverflow.com. Don't look behind.

Gregory Pakosz
+1  A: 

Really screw with his head and go for an IQueryable .foreach closure instead:

myList.ForEach(c => Console.WriteLine(c.ToString());

LOL

Terry Donaghe
I'd replace your line of code with `myList.ForEach(Console.WriteLine)`.
Mehrdad Afshari
Yeah yeah. :P ;)
Terry Donaghe
+4  A: 

"Are there any arguments I could use to help me convince him the for loop is acceptable to use?"

No, if your boss is micromanaging to the level of telling you what programming language constructs to use, there's really nothing you can say. Sorry.

Ken
I had a boss one time that wanted me to use emacs instead of vi (which I have used for 20+ years). I laughed. He got pissed. A real humjob nutcase. What can you do? Move on. Former supervisor is looking for work right now. I am employed. And he's a MS graduate from Rice. Go figure. When you micromanage the shit out of everything, you lose. Eventuallly. Hopefully.
xcramps
xcramp, it's just that emacs is losing the fight! ;-)
Michael Krelin - hacker
A: 

I think for is marginally faster than foreach in most cases, but this is really missing the point. One thing I haven't seen mentioned is that, in the scenario you're talking about (i.e., a high volume web app), the difference in performance between for and foreach is going to have no bearing on the site's performance. You're going to be limited by request/response time and DB time, not for v. foreach.

That said, I don't understand your aversion to foreach. In my opinion, foreach is usually clearer in situation where either could be used. I usually reserve for for situations where I need to traverse a collection in some ugly, non-standard way.

Sean Devlin
I like to be able to control things by index. In a foreach loop, you have to instead setup a variable and increment it inside the foreach if you need a counter. I guess if you don't need the index then I am fine with a foreach.
CoffeeAddict
That's valid. I just find in most scenarios I want to "do something" to each element. If you need to know where you are in the collection, for is definitely the way to go.
Sean Devlin
+1  A: 

It is what you do inside the loop that affects perfomance, not the actual looping construct (assuming your case is non-trivial).

Martin Wickman
A: 

Another Stackoverflow thread asking a similar question.

Chuck Conway
+2  A: 

Every language construct has an appropriate time and place for usage. There is a reason the C# language has a four separate iteration statements - each is there for a specific purpose, and has an appropriate use.

I recommend sitting down with your boss and trying to rationally explain why a for loop has a purpose. There are times when a for iteration block more clearly describes an algorithm than a foreach iteration. When this is true, it is appropriate to use them.

I'd also point out to your boss - Performance is not, and should not be an issue in any practical way - it's more a matter of expression the algorithm in a succinct, meaningful, maintainable manner. Micro-optimizations like this miss the point of performance optimization completely, since any real performance benefit will come from algorithmic redesign and refactoring, not loop restructuring.

If, after a rational discussion, there is still this authoritarian view, it is up to you as to how to proceed. Personally, I would not be happy working in an environment where rational thought is discouraged, and would consider moving to another position under a different employer. However, I strongly recommend discussion prior to getting upset - there may just be a simple misunderstanding in place.

Reed Copsey
+2  A: 

I guess this should save your ass

public IEnumerator<int> For(int start, int end, int step) {
    int n = start;
    while (n <= end) {
        yield n;
        n += step;
    }
}

usage

foreach (int n in For(1, 200, 4)) {
    Console.WriteLine(n);
}

for greater win, you may take three delegates as parameters.

Adrian