As a lead, what ownership rule would you set for disposables a C# type creates or is given, and how should its API say who disposes?
answer
- creation usually implies ownership
- parameters are borrowed by default
- factories hand ownership to the caller
- the leaveOpen family of flags
- analyzers off by default
basics
~20 sA sound rule: whoever creates a disposable disposes it; a type never disposes what it is handed unless a flag like leaveOpen says so; factory methods transfer ownership to the caller. Enable CA2000 and CA2213, which are off by default.
solid answer
~50 sI would write down three rules. First, **creation is ownership**: code that calls `new` or a factory for a disposable disposes it, with `using` for locals and a cascading `Dispose()` for fields. Second, **parameters are borrowed**: a type that receives a `Stream`, connection or handler never disposes it, unless the API asks for ownership explicitly, following the base library's convention of `leaveOpen` on `StreamWriter`, `disposeHandler` on `HttpClient` and `ownsHandle` on `SafeHandle`. Third, **a method that returns a disposable transfers ownership** to the caller, and its name and docs make that obvious; properties should not hand out objects the caller is expected to dispose. Then enforce it: CA2000 and CA2213 are not enabled by default in .NET 10, so turn them on, accept their documented ownership-transfer assumptions, and require a justification on every suppression. The cost is some analyzer noise and a few explicit flags; the gain is that review stops arguing about who disposes.
go deeper
Recall the basic rule: the code that creates a disposable is the code that disposes it, and parameters are usually borrowed.
Explain how leaveOpen, disposeHandler and ownsHandle express ownership in constructors, and that the stream wrappers default to owning.
Show how CA2000 and CA2213 check ownership, where their Stream ownership-transfer assumption conflicts with borrowed parameters, and how to resolve it.
Own the written convention and its enforcement: default to borrowed parameters, explicit ownership flags, ownership-transferring factories, and justified suppressions, weighing analyzer noise against leak and double-dispose risk.
## Why a team needs a written rule C# gives you the mechanics of cleanup (`IDisposable`, `using`, cascading `Dispose()`), but not the **policy** of who calls `Dispose()` on an object that several pieces of code can reach. Without a rule, two failure modes alternate in a codebase: - **Leaks:** nobody disposes, each side assuming the other will. File handles and connections stay open until finalization, if their types even have a finalizer. - **Premature disposal:** both sides dispose, or the wrong side does, and the real owner later gets `ObjectDisposedException`. The .NET documentation's starting point is that a class that creates a disposable and stores it is typically responsible for its cleanup, but that ownership can be transferred. A lead's job is to turn "typically" into a convention everyone can apply without debate. ## A rule set that works 1. **Creation is ownership.** Whoever calls the constructor or the factory owns the result. Locals go in `using`; fields are disposed by the owning type's `Dispose()`, which makes that type `IDisposable` in turn. 2. **Parameters are borrowed.** A method or constructor that receives a disposable uses it and leaves it alone. The caller created it, so the caller disposes it. 3. **Taking ownership is explicit.** When a type genuinely needs to own what it is given (a wrapper meant to be the only handle on a stream), it says so in its signature with a boolean that names the direction, and documents the default. 4. **Returning transfers ownership.** A method that returns a newly created disposable hands it to the caller, who must dispose it. Name such methods so the transfer reads naturally (`Open...`, `Create...`) and never return an object the method put in a `using` first. 5. **Properties do not transfer.** A property that exposes an internal disposable is a view into the owner's state; callers must not dispose it, and the owner's `Dispose()` remains the only path. ## Follow the base library's vocabulary The base class library already has a convention for rule 3, and matching it makes APIs predictable: | Type | Parameter | Meaning when `true` | Default | |---|---|---|---| | `StreamWriter`, `StreamReader` | `leaveOpen` | Do not dispose the stream | `false` (owns it) | | `BinaryWriter`, `BinaryReader` | `leaveOpen` | Do not dispose the stream | owns it (constructors without the flag) | | `HttpClient` | `disposeHandler` | Dispose the handler | `true` (the one-argument constructor) | | `SafeHandle` subclasses | `ownsHandle` | Release the native handle | chosen by the subclass | Note that the stream wrappers default to **owning**, which is the opposite of rule 2 and the source of a common bug: a method wraps a caller's stream in a `StreamWriter`, disposes the writer, and closes the caller's stream. Your rule can still say "borrowed by default" for your own types, but reviewers must know that a BCL wrapper constructed without `leaveOpen: true` takes the stream with it. ## Enforcement: analyzers plus review Two analyzer rules check ownership mechanically, and neither is enabled by default in .NET 10: - **CA2000**, "Dispose objects before losing scope", reports a local disposable that is not disposed before its last reference goes away. It treats passing a `Stream`, `TextReader`, `TextWriter` or `IResourceReader` to a constructor as an ownership transfer. - **CA2213**, "Disposable fields should be disposed", reports a field holding a disposable the type created that its `Dispose()` never disposes, and also a constructor-supplied `Stream`-like field, which it assumes is owned. Enable them for production projects, and make every suppression carry a justification that names the actual owner. Their assumptions will sometimes disagree with rule 2 for stored streams; that is where an explicit ownership flag earns its place. Configuring severities and suppressions is ordinary analyzer setup, the same as for any other rule. ## Trade-offs a lead should weigh - **Noise vs. coverage.** Data-flow rules produce false positives, especially across helper methods. Starting at warning level on new code and suppressing with reasons is cheaper than fighting a wall of errors. - **Flags vs. simplicity.** Every `leaveOpen`-style parameter adds a mode to test. Offer one only where callers really need both behaviours; otherwise pick one and document it. - **Factories vs. constructors.** A factory that returns an owned disposable is clear when named well, but returning cached or shared instances from the same method breaks rule 4. Shared instances belong behind a type that is not disposable to its callers, or behind a container that owns them. - **Tests.** For any API that borrows a disposable, a test should use the object after the call; for any API that takes ownership, a test should check it was disposed.
- A method returns a FileStream it opened. How do you make the ownership transfer unmistakable?Name it for what it does, such as `OpenReportFile`, document in its XML comment that the caller must dispose the result, and never wrap the stream in `using` inside the method. CA2000 does not flag a disposable the method returns, since the caller now owns it; inside the method, dispose the stream only on the failure path before rethrowing, so a half-initialised object does not leak.
- Why would you not simply make every type dispose every disposable it can reach, to be safe?Because disposal is not harmless to the owner. Disposing a borrowed stream, connection or handler breaks the code that created it, often far away and later, as an `ObjectDisposedException`. Leaks are usually slower and quieter to surface; premature disposal fails in production paths. An explicit owner avoids both.
- Where do you draw the line between this rule and a dependency-injection container's lifetimes?Objects resolved from a container are owned by the container, so application code treats them as borrowed and never disposes them; that is the same rule 2 applied to a different creator. How the container itself disposes services belongs to the hosting framework, not to this language-level convention.
- Any type holding a disposable reference should dispose it to be safe
- StreamWriter leaves the stream open unless told otherwise
- CA2000 and CA2213 are on by default, so no setup is needed
- Returning an object from inside a using statement transfers it safely
- Ownership only matters for types with finalizers