C# Range-Foreach Syntax Extensions
Provides the range-foreach syntax for C# 9.0 or higher.
Supported frameworks:
- .NET Framework >= 3.5
- .NET Core >= 1.0
- .NET Standard >= 1.0
Range-Foreach Syntax
Reference source files or the NuGet package to write foreach loops like this:
foreach (var index in 0..100)
{
// loop body...
}
which is equivalent to the legacy for loop below:
for (int index = 0; index < 100; index++)
{
// loop body...
}
TIPS: 0 can be omitted in range expressions, e.g. ..100 (equivalent to 0..100).
NOTE: Use ^ to represent negative numbers, e.g. ^100..0 (instead of -100..0).
Stepped Syntax
Use the Step method to write foreach loops like this:
foreach (var index in (99..^1).Step(-2))
{
// loop body...
}
which is equivalent to the legacy for loop below:
for (int index = 99; index > -1; index -= 2)
{
// loop body...
}
Dependency Type Polyfill
This syntax requires the System.Range type (and also the System.Index type).
Considering that early frameworks do not provide this type, this project includes the polyfill source.
If a third party package that includes the System.Range type (such as IndexRange, etc.) is referenced,
define the INDEX_RANGE_EXTERNAL constant in the project file to avoid duplicate definitions:
<DefineConstants>$(DefineConstants);INDEX_RANGE_EXTERNAL</DefineConstants>
Performance Benchmark
BenchmarkDotNet v0.13.10, Windows 11 (10.0.22631.2792/23H2/2023Update/SunValley3)
AMD Ryzen 7 5800H with Radeon Graphics, 1 CPU, 16 logical and 8 physical cores
.NET SDK 8.0.100
[Host] : .NET 8.0.0 (8.0.23.53103), X64 RyuJIT AVX2
DefaultJob : .NET 8.0.0 (8.0.23.53103), X64 RyuJIT AVX2
| Method | LoopCount | Mean | StdDev | Ratio | Code Size |
|---|
|