user16276760
user16276760

Reputation:

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

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?

Upvotes: 0

Views: 188

Answers (2)

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239664

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.

Upvotes: 4

0x0000000000000
0x0000000000000

Reputation: 166

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

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

Upvotes: 0

Related Questions