Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using vs lambda [closed]

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?

like image 816
dotneter Avatar asked Feb 04 '10 13:02

dotneter


People also ask

Is a lambda the same as a closure?

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.

Why a lambda expression forms a closure?

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.

Does C# support closures?

In C#, closures are supported using anonymous methods, lambda expressions, and delegates.

Are Python lambdas closures?

The Python lambda function on line 4 is a closure that captures n , a free variable bound at runtime.


1 Answers

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?

like image 178
Mark Seemann Avatar answered Oct 22 '22 06:10

Mark Seemann