Why use null conditional operator when a variable that can't be null?

186 Views Asked by At

I saw the below code from MSDN:

using System;

public sealed class Foo : IDisposable
{
    private readonly IDisposable _bar;

    public Foo()
    {
        _bar = new Bar();
    }

    public void Dispose()
    {
        _bar?.Dispose();
    }
}

I don't understand why it needs to use _bar?.Dispose(); instead of _bar.Dispose();?

_bar has been declared readonly and initialized in the constructor, so _bar will not be null and cannot be reassigned to null, then why do we need to do the null check on _bar?

2

There are 2 best solutions below

0
On

This is just for cleaner code. Just make the null checks in all you Dispose().

But technically, yes actually it's not an requirement.

0
On

In this specific case it's redundant. However, a slightly more complex constructor may allow this to escape1 before invoking the Bar constructor and, of course, the Bar constructor could then throw, leaving the field unassigned.

If Dispose were then to be invoked on this partially constructed Foo, it would be null. This is slightly contrived but, there again, you're not expected to just literally have a Foo class that just wraps a Bar and does nothing else.


1Which you're also not doing ideally but it's valid to do so, however ill-judged it may be. This is required so that something is capable of calling the Dispose method on the instance.