There are several pattern-features of C# language, i.e. classes need not derive from a specific interface; but rather implement a certain pattern in order to partake in some C# syntax/features.
Let’s consider an example:
public class MyCollection : IEnumerable
{
public T Add(T name, T name2, ...) { }
public IEnumerator GetEnumerator() { return null; }
}
Here, TYPE is any type. Basically we have a class that implements IEnumerable and has a method named Add() with any number of parameters.
This enables the following declaration of a new MyCollection instance:
new MyCollection{{a1, a2, ...}, {b1, b2, ...} }
Which is equivalent to:
var mc = new MyCollection();
mc.Add(a1, a1, ...);
mc.Add(b1, b2, ...);
Magic! Meanwhile, recently (I believe during the BUILD event) Anders Hejlsberg let slip that the new await/async will be implemented using patterns as well, which lets WinRT get away with returning something other than Task<T>.
So my question is twofold,
- What is the pattern Anders was talking about, or did I misunderstand something? The answer should be somewhere between the type WinRT provides, something to the effect of
IAsyncFooand the unpublished specification. - Are there any other such patterns (perhaps already existing) in C#?
The draft specification is published – you can download it from the Visual Studio home page. The pattern for async is the one given in driis’s answer – you can also read my Eduasync blog series for more details, with this post being dedicated to the pattern.
Note that this pattern only applies to “what you can await”. An async method must return
void,TaskorTask<T>.In terms of other patterns in C# beyond the collection initializer you mentioned originally:
foreachcan iterate over non-IEnumerable implemenations, so long as the type has aGetEnumeratormethod returning a type which hasMoveNext()andCurrentmembersSelect,Where,GroupByetc.