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?
This is just for cleaner code. Just make the null checks in all you Dispose().
But technically, yes actually it's not an requirement.