Dear Reader,
Further to my first post here, today i noticed some thing cool with respect to Using blocks in C#. We all know that in using block, usually we create a type which implements IDisposable as shown below:
public class MyClass : IDisposable
{
public void Dispose()
{
Console.WriteLine("Disposed");
}
}
And the usage code looks like:
using (MyClass m = new MyClass()) { }
Infact all these days i have been doing the same w.r.t using() blocks in all my code. But today i learned (yes a real shame) that you need not always create a type, rather call a method in it actually. Lemme show you a code on the same:
public class MyClass : IDisposable
{
public void Dispose()
{
Console.WriteLine("Disposed");
}
}
public class UsingClass
{
public static MyClass SomeMethod()
{
return new MyClass();
}
}
public partial class Program
{
public static void Main()
{
using (UsingClass.SomeMethod()){ }
Console.ReadLine();
}
}
Here, compiler has gone a bit smart here because it efficiently sees that the return type of the method SomeMethod() is returning a type which implements IDisposable, hence it does not issue any error. Just remove the type implementing IDisposable, then you would get error.
Your comments are welcome
Happy Coding.


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();
}
Yes you could do that too, but your not utilizing much of what your doing with the created instance right.
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.
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.
Yep, your right.