The following code produces no errors when executed:
using ((IDisposable)null) {
Console.WriteLine("A");
}
Console.WriteLine("B");
Is a null value to using
'allowed'? If so, where is it documented?
Most C# code I've seen will create a "dummy/NOP" IDisposable object - is there a particular need for a non-null Disposable object? Was there ever?
If/since null is allowed, it allows placing a null guard inside the using statement as opposed to before or around.
The C# Reference on Using does not mention null values.
The using statement causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and can't be modified or reassigned. A variable declared with a using declaration is read-only.
The using statement is used to set one or more than one resource. These resources are executed and the resource is released. The statement is also used with database operations. The main goal is to manage resources and release all the resources automatically.
By default, the garbage collector automatically calls an object's finalizer before reclaiming its memory. However, if the Dispose method has been called, it is typically unnecessary for the garbage collector to call the disposed object's finalizer.
IDisposable is an interface that contains a single method, Dispose(), for releasing unmanaged resources, like files, streams, database connections and so on.
Yes, a null value is allowed. §8.13, "The using statement", of the C# 5.0 specification says:
If a
null
resource is acquired, then no call toDispose
is made, and no exception is thrown.
The specification then provides the following expansion for a using
statement of the form
using (ResourceType resource = expression) statement
when resource
is a reference type (other than dynamic
):
{
ResourceType resource = expression;
try {
statement;
}
finally {
if (resource != null) ((IDisposable)resource).Dispose();
}
}
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