Search code examples
c#compiler-constructiondispose

Can Compilers targeting CLR generate Dispose method call when object is set to null?


Can compilers (for e.g. C#) automatically generate call to Dispose method on the object when it is set to null (of course, object should support Dispose method in first place). For example, if we write

cnSqlConnection = null;

and cnSqlConnection is an instance of type SqlConnection, can C# compiler inject Dispose method call right before updating reference to null?

Also, since framework classes do support scenario where Dispose method might get called multiple times, there would be no harm if the call is duplicated.


Solution

  • (a) A correctly-implemented object should perform the same cleanup logic in its finalizer. If you omit the call to Dispose, the finalizer logic will probably run anyway.

    (b) Raymond Chen explains the complexity of auto-dispose here. In summary: it's only really safe to get a human programmer to call Dispose at the right point. If you take auto disposal to its logical conclusion then you end up with reference counting, which is what the CLR memory model sets out to avoid.