Disposable patterns in structs and ref structs
Over time, C# introduced some pattern-based constructs to resolve issues deriving from rules that could not be applied in every circumstance. This happens, for example, with the foreach
statement not requiring an object to implement the IEnumerable<>
interface, instead just relying on the presence of the GetEnumerator
method, and similarly the object returned by GetEnumerator
not needing to implement IEnumerator
but just exposing the required members instead.
This change was driven by the recent introduction of the ref structs
, which are important for diminishing the pressure on the garbage collector as they are guaranteed to live only on the stack but do not allow the implementation of interfaces.
The pattern-based approach has now been extended to the Dispose
and DisposeAsync
methods under certain conditions that we are going to discuss now.
Starting from C# 8, developers can define Dispose
or DisposeAsync
without implementing...