In my Dispose methods (like the one below), everytime i want to call someObj.Dispose() i also have a check for someObj!=null.
Is that because of bad design on my part?
Is their a cleaner way to ascertain that Dispose of all the members (implementing IDisposable) being used in an object is called without having a risk of NullReference exception ?
protected void Dispose(bool disposing)
{
if (disposing)
{
if (_splitTradePopupManager != null)
{
_splitTradePopupManager.Dispose();
}
}
}
Thanks for your interest.
Maybe someone else can chime in on this, but I don’t personally think it’s a design flaw — just the safest way to do it.
That said, nothing’s stopping you from wrapping your
nullcheck andDisposecall in a convenient method:Then your
Disposemethod could look a bit cleaner:As an added bonus, this also resolves a potential race condition in your original code. If running in a multithreaded context, the
if (_field != null) _field.Dispose()pattern can result in aNullReferenceExceptionwhen_fieldis set tonullbetween the check and the disposal (rare, but possible). Passing_fieldas an argument to a method such asDisposeMembercopies the reference to a local variable in the method, eliminating this possibility, unlikely as it is.