6 comments on “Method call in Using block TIP

  1. using just using (new MyClass()) { } should work as well, because all you do normally is store it in a variable and use that all over the place. Nothing however is stopping you from typing the create without a variable declaration.

    You could use this as well:

    using(new MyClass())
    {
    Console.WriteLine(“lol”);
    SomeMethodDefinedOnMyClass();
    }

  2. Specifically, the using() block will accept *any* expression that is implicitly convertible to IDisposable, including variable-declaration expressions.

    The only exception I know of is “using (null) {}” even though “null” is implicitly convertible to any reference type. (Note that “using ((IDisposable)null) {}” will compile and execute without error, as expected.)

    • Yep, even when i made the method to return a null instead of the type instance, still the compiler just passes it. And strange that even there is no run time exception being thrown. I guess one has to be careful on this.

  3. There is no runtime exception because the using() block includes a null check. “using (foo) { … }” is syntactic sugar for:

    IDisposable temp = foo;
    try {

    } finally {
    if (temp != null) temp.Dispose();
    }

    The temporary local is only generated when the target expression of the using block is not a variable declaration, but the null check is emitted in both cases.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s