Generator pattern in C# .NET
Boo language has nice code pattern called Generator:
// Generator expressions are defined through the pattern:
<expression> for <declarations> in <iterator> [if|unless <condition>]
// Generator expressions can be used as return values:
def GetCompletedTasks():
return t for t in _tasks if t.IsCompleted
// Generator expressions can be stored in variables:
oddNumbers = i for i in range(10) if i % 2
This pattern simply creates some IEnumerable object via the syntax transformation. We can not have this sugar in C# yet, but that’s how we can leverage the concept:
// Simple syntax
var customerList = new List<Customer>();
for (int i = 0; i < 40; i++)
{
customerList.Add(new Customer
{
Name = "Customer_" + i
});
}
// generator + LINQ syntax
var customers = Generator.For(40).Select(i => new Customer
{
Name = "Customer_" + i
});
Both pieces of code do the same thing; they create enumeration of 40 Customers with names in “Customer_[ID]” format.
The first approach is the traditional one, while the second uses Generator to create enumerator from 0 to 40 (with lazy evaluation) and then LINQ to transform enumerator entries into Customers.
I’m not sure if the generator could be useful in the base code, but it does speed up writing some unit tests a little bit. Here is the sample backing Generator method:
public static class Generator
{
public static IEnumerable<int> For(int max)
{
for (int i = 0; i < max; i++)
{
yield return i;
}
}
// ...
3 Comments to Generator pattern in C# .NET
Unless I miss something, there’s already a built-in one in System.Linq:
Enumerable.Range(0, 40).Select(i => new Customer{Name = “Name_” + i});
aCoder,
yes, you are absolutely right.
[...] you remember my post on the Generator pattern? If you only need a numeric inline generator, then System.Linq already provides one. Look out for [...]
Leave a comment
Search
Archives
Recent Comments
- aCoder on Extension methods for interfaces
- Requirements for the Photon .NET project | Rinat Abdullin on IRepository, cross-cutting concerns and flexibility
- Nicholas Blumhardt on Extension methods for interfaces
- aCoder on IRepository, cross-cutting concerns and flexibility
- Rinat Abdullin on Blog upgraded
- Rinat Abdullin on Extension methods for interfaces
- IRepository, cross-cutting concerns and flexibility | Rinat Abdullin on Extension methods for interfaces
- Bill Pierce on Blog upgraded
- aCoder on Extension methods for interfaces

July 21, 2008