Is it equivalent?
public static void Using<T>(this T disposable, Action<T> action)
where T:IDisposable
{
try {
action(disposable);
}
finally {
disposable.Dispose();
}
}
new SqlConnection("").Using(conn => {
});
using(var conn = new SqlConnection("")){
};
in other words, can we replace using keyword with this method?
A lambda expression is an anonymous function and can be defined as a parameter. The Closures are like code fragments or code blocks that can be used without being a method or a class. It means that Closures can access variables not defined in its parameter list and also assign it to a variable.
a function that can be treated as an object is just a delegate. What makes a lambda a closure is that it captures its outer variables. lambda expressions converted to expression trees also have closure semantics, interestingly enough.
In C#, closures are supported using anonymous methods, lambda expressions, and delegates.
The Python lambda function on line 4 is a closure that captures n , a free variable bound at runtime.
I don't think this is a particularly good idea, because it would also allow us to write
var conn = new SqlConnecction("");
conn.Using(c => /* do something with c */);
conn.Open();
This would compile, but when you reach the last line, it will throw an ObjectDisposedException.
In any case, the using
coding idiom is well-known, so why make it harder for your fellow developers to read your code?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With