© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•15mo ago•
27 replies
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
CA2000
as an error is also turned on.

Consider a method that returns a type that implements
IDisposable
IDisposable
and needs to either return it, or ensure it gets
Dispose
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();
  }
}
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
malloc
and
free
free
in C.
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

IDisposable Constructor Injection
C#CC# / help
12mo ago
❔ Service provider, IDisposable
C#CC# / help
3y ago
✅ Implementing IDisposable properly
C#CC# / help
3y ago
IDisposable and using keyword?
C#CC# / help
2y ago