C# – Enumerable.Range – When does it make sense to use

.netc++linq

When programming it's almost instinctive deciding when to use a for loop, or foreach, but what is the determining factors or problem space for choosing to use Enumerable.Range?

A For Loop is chosen when we want to iterate a set number of times (over a simple data type) to calculate/do a repetitive task.

A For Each is similar, but chosen when we want to iterate over a list of complex objects to calculate/do a repetitive task.

Again, what's the determining factors for using an Enumerable.Range?

IEnumerable<int> squares = Enumerable.Range(4, 3).Select(x => x * x);

Best Solution

foreach is about iterating over an existing set/collection.

Enumerable.Range is for generating a set/collection. You wouldn't, generally, want to write a for loop just to generate a set if it can be generated by Enumerable.Range - you'd just be writing boilerplate code that's longer and requires you to allocate some kind of storage (e.g. a List<int>) to populate first.