C# 2008
I have been working on this for a while now, and I am still confused about the use of finalize and dispose methods in code. My questions are below:
Using lambdas instead of IDisposable.
I have never been thrilled with the whole using/IDisposable idea. The problem is that it requires the caller to:
My new preferred method is to use a factory method and a lambda instead
Imagine I want to do something with a SqlConnection (something that should be wrapped in a using). Classically you would do
using (Var conn = Factory.MakeConnection())
{
conn.Query(....);
}
New way
Factory.DoWithConnection((conn)=>
{
conn.Query(...);
}
In the first case the caller could simply not use the using syntax. IN the second case the user has no choice. There is no method that creates a SqlConnection object, the caller must invoke DoWithConnection.
DoWithConnection looks like this
void DoWithConnection(Action action)
{
using (var conn = MakeConnection())
{
action(conn);
}
}
MakeConnection
is now private