I'm trying to refresh my memory on C# and using pattern.
Is there a possibility to have some control flow be executed automatically on exception?
For instance:
class Test : IDisposable
{
public void Dispose()
{
Console.WriteLine("ok");
}
public void XX()
{
Console.WriteLine("KO");
}
}
using (new Test())
{
}
// prints "ok"
using (new Test())
{
throw new Exception();
}
// this would print "KO"
Is there a way to achieve this effect in C# ? Example of use case would be : a database system where I want to commit result on correct execution, but rollback on exception
For example, currently to handle transaction commits/rollback, it's possible to do this :
using(var tran = conn.BeginTransaction())
{
try
{
// DO WORK
tran.Commit();
} catch {
tran.Rollback();
throw;
}
}
But this means that clients of "tran" object have to correctly write the try/catch code. I'm looking for a way to provide the same functionality out of the box, so that users just have to write the "DO WORK" code (and the "using") and not have to write the "using" and the try/catch code
Actiondelegate and wrap that inside the try/catch you have in your example? The user would then provide theDoWorkviaActiondelegate and you would handle the try/catch for them.