Generic Closure
Sometimes you are unable to use generics at the class level. For example, within Windows.Forms, using class-level generic arguments breaks the designer. One solution is to use what I call a “Generic Closure”. Basically, you can use a generic argument at the method level and then save a block that captures some usage of the generic type. E.g.
delegate object Creator(); Creator _newT; void Foo<T>() where T : new() { _newT = delegate { return new T(); } } // then invoke the delegate sometime later: object t = _newT();
In this example the generic closure serves two purposes:
- It enforces a default public constructor.
- It allows us to new up a T without resorting to reflection.
Obviously, being able to use class level generics in this context is preferable so lets hope it gets baked in completely some time soon.
Trackbacks
Use this link to trackback from your own site.


