Resource Acquisition is Initialization in C#

Resource Acquisition Is Initialization (RAII) is a pattern I grew to love when working in C++.  It is perfectly suited for resource management such as matching all those pesky new's and delete's.  One of my goals was to limit the explicit deallocation statements I had to write.  Often these statements became victims of run-time control flow changes (i.e. exceptions, unhappy path) or development-time code refactoring.

The beauty of RAII is realized by tying your resource creation (acquisition) to the construction (initialization) of a class instance.  Then bind the resource deallocation to the destruction of that instance.  That is well and good in a language with strong destructor semantics like C++, but languages like C# that run on garbage-collecting runtimes don't provide the same instance lifetime guarantees.

Here is a class and sample that combines a few features of C# to provide an RAII-like solution:

using System;

namespace RAII { public class DisposableDelegate : IDisposable { private Action dispose;

    public DisposableDelegate(Action dispose)
    {
        if (dispose == null)
        {
            throw new ArgumentNullException("dispose");
        }

        this.dispose = dispose;
    }

    public void Dispose()
    {
        if (this.dispose != null)
        {
            Action d = this.dispose;
            this.dispose = null;
            d();
        }
    }
}

class Program
{
    static void Main(string\[\] args)
    {
        Console.Out.WriteLine("Some resource allocated here.");

        using (new DisposableDelegate(() => Console.Out.WriteLine("Resource deallocated here.")))
        {
            Console.Out.WriteLine("Resource used here.");

            throw new InvalidOperationException("Test for resource leaks.");
        }
    }
}

}

The output of this program is:

Some resource allocated here. Resource used here.

Unhandled Exception: System.InvalidOperationException: Test for resource leaks. at RAII.Program.Main(String[] args) in c:\Dev\RAII\RAII\Program.cs:line 40 Resource deallocated here.

Code without fear!

--Don

This article is part of the GWB Archives. Original Author: codeWithoutFear

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.