14

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.

user2864740
  • 60,010
  • 15
  • 145
  • 220
  • 2
    The article you've mentioned links to specification (which is the source of truth - https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/statements#the-using-statement) as well shows how it is expanded - `if (font1 != null) ((IDisposable)font1).Dispose();` with definitive check for null result... So is your actual question about "is there a particular need for a non-null Disposable [dummy] object"? โ€“ Alexei Levenkov Oct 24 '17 at 03:19
  • @AlexeiLevenkov Which by answering the other question is "technically no" - I suppose a dummy instance could still be useful when the object had other properties that may be accessed without wanting to burden the caller. I don't know why I completely glazed over that example.. thanks for pointing it out. โ€“ user2864740 Oct 24 '17 at 18:03

1 Answers1

23

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();
    }
}
Michael Liu
  • 52,147
  • 13
  • 117
  • 150
  • 1
    Link to the specification can be found from article mentioned in the question - https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/statements#the-using-statement โ€“ Alexei Levenkov Oct 24 '17 at 03:20