I was refactoring some the other day, I bumped into something like that:
public async Task<Result> Handle(CancelInitiatedCashoutCommand command, CancellationToken cancellationToken)
{
using (_logger.BeginScope("{@CancelCashoutCommand}", command))
{
return await GetCashoutAsync(command.CashoutId)
.Bind(IsStatePending)
.Tap(SetCancelledStateAsync)
.Tap(_ => _logger.LogInformation("Cashout cancellation succeeded."));
}
}
and ReSharper suggested to refactor it as:
public async Task<Result> Handle(CancelInitiatedCashoutCommand command, CancellationToken cancellationToken)
{
using var scope = _logger.BeginScope("{@CancelCashoutCommand}", command);
return await GetCashoutAsync(command.CashoutId)
.Bind(IsStatePending)
.Tap(SetCancelledStateAsync)
.Tap(_ => _logger.LogInformation("Cashout cancellation succeeded."));
}
I am a bit skeptical, actually I am not sure when the implicit Dispose
call will happen with the second version.
How can I know?
using var scope = ... ;
means thatscope
will beDisposed
on leavingHandle
scope – Foetorpublic class TestDispose : IDisposable { public void Dispose(){ Console.WriteLine("disposing"); }}
to see when the output is called. – Doublefacedusing var
is useful if, functionally, you don't really care when exactly the resource is disposed as long as it happens (e.g.SqlConnection
). In all cases theDispose
moment is deterministic, but with ausing var
the scope can be left unsaid when it's not particularly important. Of course this is subjective and that's why Resharper sticks to suggestions. – Meghan