I wish we have "Usable" pattern in C#, when code block of using construct would be passed to a function as delegate:
class Usable : IUsable
{
public void Use(Action action) // implements IUsable
{
// acquire resources
action();
// release resources
}
}
and in user code:
using (new Usable())
{
// this code block is converted to delegate and passed to Use method above
}
Pros:
- Controlled execution, exceptions
- The fact of using "Usable" is visible in call stack
Cons:
- Cost of delegate
Do you think it is feasible and useful, and if it doesn't have any problems from the language point of view? Are there any pitfalls you can see?
EDIT: David Schmitt proposed the following
using(new Usable(delegate() {
// actions here
}) {}
It can work in the sample scenario like that, but usually you have resource already allocated and want it to look like this:
using (Repository.GlobalResource)
{
// actions here
}
Where GlobalResource (yes, I know global resources are bad) implements IUsable. You can rewrite is as short as
Repository.GlobalResource.Use(() =>
{
// actions here
});
But it looks a little bit weird (and more weird if you implement interface explicitly), and this is so often case in various flavours, that I thought it deserve to be new syntactic sugar in a language.