C#C
C#14mo ago
Olipro

IDisposable ownership semantics

This is primarily a question regarding whether or not C# has introduced any sort of syntactic sugar or support for a "nicer" way of expressing transfer of ownership.

For the purposes of this question, nullable types is fully enabled and static analysis that will issue CA2000 as an error is also turned on.

Consider a method that returns a type that implements IDisposable and needs to either return it, or ensure it gets Dispose'd if an exception occurs - Currently I'd write something like this:

public SomeDisposable getDisposable() {
  var result = new SomeDisposable();
  try {
    //do possibly exception-throwing stuff here
    var ret = result;
    result = null;
    return ret;
  } finally {
    result?.Dispose();
  }
}


Is there anything better than this? This sort of pattern feels about as manual as malloc and free in C.
Was this page helpful?