How to handle disposable objects?
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?
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?
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