FluentResults icon indicating copy to clipboard operation
FluentResults copied to clipboard

How to handle disposable objects?

Open vyeghikyan-st opened this issue 1 year ago • 2 comments

Let us have a class

public class MyClass{
  // Some methods, variables and constructors
  
  public Result<Stream> OpenStream() {
   // Implementation
  }

}

The only pattern I can think of for handling the returned object is as follows:

var instance = new MyClass(..);

var streamReasult = instance.OpenStream();

if(streamResult.IsFailed){
  return Result.Fail<...>(...);
}

try{
  // Do my stuff with the stream
}
finally{
  streamResult.Value.Dispose();
}

Is there a better way?

vyeghikyan-st avatar Oct 23 '24 06:10 vyeghikyan-st

Apart from the fact that you probably should be using using (var stream = streamResult.Value), your implementation looks correct. Why not use an exception if the stream fails to open, though?

Feijo avatar Dec 19 '24 09:12 Feijo

Having the same issue. Using Microsoft's IDisposableAnalyzers to catch incorrect dispose usage. Problem is that it can't catch when a disposable object is stored in a Result. You can't create an analyzer for this case. Something should always "own" a disposable object and it's the owners responsibility to dispose of its disposable objects. In this case the Result is the owner but it doesn't dispose of the object.

Perhaps we need a DisposableResult which implements IDisposable and IAsyncDisposable? Not sure how that would mesh with the rest of FluentResults.

Use case:

using DisposableResult<Stream> stream = GetStreamOrSomething();
if (stream.IsFailed)
{
    return stream;
}

// Use stream

agra6475 avatar Apr 28 '25 14:04 agra6475