Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a null IDisposable value with the using statement

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.

like image 556
user2864740 Avatar asked Oct 24 '17 02:10

user2864740


People also ask

What is using () in C#?

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.

What is the use of using statement in C# with example?

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.

Is IDisposable called 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.

What is IDisposable?

IDisposable is an interface that contains a single method, Dispose(), for releasing unmanaged resources, like files, streams, database connections and so on.


1 Answers

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 to Dispose 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();
    }
}
like image 170
Michael Liu Avatar answered Oct 19 '22 04:10

Michael Liu