Click here to Skip to main content
Click here to Skip to main content

RAII (Resource Acquisition Is Initialization) C# Helper Classes

, 29 Oct 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
Some useful RAII C# helper classes for functionality that does not implement IDisposable


What the Heck is RAII?

RAII stands for "Resource Acquisition Is Initialization". It is a programming idiom which ensures that there is no resource leak (like lost memory, open handles, dangling critical section monitors, etc.), even if an exception is thrown. For languages like C#, the lost memory is not of an issue, but the problem of "open handles" and "critical section monitors" is equally important.

Some languages provide a mechanism to deterministically and implicitly call one specific function at the end of the lifetime of an object instance (e.g. the destructor in C++). The RAII idiom in C++ takes benefit of that fact and places the "acquisition" of the resource into the constructor (= initialization), and releases the resource in the destructor.

E.g. the C++ auto pointer as well as any guard or sentry classes are implementing the RAII idiom. For more insight, see RAII Idiom.

In C++, a reporting sentry (RAII class) would log the text in its constructor and log again some text in its destructor (that is called when leaving the function body):

// this is C++ use of an RAII class
void f()
   ReportSentry reportSentry("function f");

C# does not know this deterministic and implicit destructor call, that's why I explain how I approach this issue in C#.

RAII in the C# World

Coming from a C++ background, I often did apply the RAII idiom. This was not only used for resources but for any kind of action that required symmetric "open-close", "add-remove", "set-reset", "open tag - close tag", "enter critical section - leave critical section", "report start-of-function - report end-of-function", etc. actions - no matter how the control flow left the current scope.

C# provides the well known IDisposable interface. Each class that implements this interface can be considered as "RAII-ready", i.e., one can use an instance of this class in a...

using (...) { ... }


But what to do if you have the need of RAII, but no class at hand for the using (...) { ... } statement?

This article shows some simple helper classes that provide an IDisposable wrapper class for an init and a cleanup delegate.

Of course, this is not at all rocket science - actually, it is very simple. It should help to clear up the mist of exception handling involved and focus on the normal control flow.

Using the Code

First, I show the two usages of RAII versus hand crafted side by side.

With RAII support classes Hand crafted
using (var objGuard = new RAIIGuard<int>(
                  () =>objStack.Pop(),
    if (objGuard.Item != 0)
    if (...)
         throw new ...;
int iTaken;
bool bTaken = false;
    // access the taken object
    iTaken = objStack.Pop();
    bTaken = true; 
    if (iTaken == 0)
    if (...)
         throw new ...;
    if (bTaken)

I consider the RAII supported approach more legible. If the lambda expressions hurt your eyes, you can always use delegates or methods, e.g.

private int Pop() { return Stack.Pop(); }
private void Push(int i) { Stack.Push(i); }
using (var objGuard = new RAIIGuard<int>(Pop, Push)) 

Conveniently, there are two classes to provide that function:

  1. one that has an init action and a cleanup action (e.g. login, logout)
  2. one that has an init function returning an object and a cleanup function taking that object (e.g. login and logout with a session object)
// used for symmetric actions like login, logout
public sealed class RAIIGuard: IDisposable
    private Action Cleanup { get; set; }
    public RAIIGuard(Action init, Action cleanup)
        Cleanup = cleanup;
        if (init != null) init();
    void IDisposable.Dispose() { if (Cleanup != null) Cleanup(); }
// used for symmetric actions that must pass
// over an object from init to cleanup and that
// need to provide the item to the "using" body
public sealed class RAIIGuard<T>: IDisposable
    private Action<T> Cleanup { get; set; }
    public T Item { get; private set; }
    public RAIIGuard(Func<T> init, Action<T> cleanup)
        Cleanup = cleanup;
        Item = (init != null) ? init() : default(T);
    void IDisposable.Dispose() { if (Cleanup != null) Cleanup(Item); }


It would still be nice if the committee "guarding" Wink | ;-) the C# language could re-consider to implement a native RAII support (e.g. where one can declare a guard as an instance of some kind of "value" type and at the end of the scope, a "Dispose" method is implicitly and deterministically called).

The approach above still requires a certain amount of cooperation by the client where as the pure RAII solution would not need cooperation by the client, i.e., in C#, one can still screw up the RAII idiom by not calling the Dispose() method Frown | :-( .

In the meantime, the approach shown above is good enough for me...


  • 2010-10-27 Initial version
  • 2010-10-27 Fixed some typos
  • 2010-10-29 Added more background on RAII, explicit implementation of Dispose() (Thanks to Roberto Collina)


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Andreas Gieriet
Founder eXternSoft GmbH
Switzerland Switzerland
I feel comfortable on a variety of systems (UNIX, Windows, cross-compiled embedded systems, etc.) in a variety of languages, environments, and tools.
I have a particular affinity to computer language analysis, testing, as well as quality management.
More information about what I do for a living can be found at my LinkedIn Profile and on my company's web page (German only).
Follow on   LinkedIn

Comments and Discussions

QuestionA slight modification PinmemberTobiasP14-Feb-12 8:19 
AnswerRe: A slight modification PinmemberAndreas Gieriet14-Feb-12 13:27 
GeneralRe: A slight modification PinmemberTobiasP15-Feb-12 0:56 
Generalthanks for sharing - have 5 PinmemberPranay Rana17-Jan-11 2:24 
GeneralMy vote of 5 PinmemberWizzard01-Nov-10 19:02 
GeneralRAII-guarding fields in Pinmembersupercat931-Oct-10 20:54 
I've come up with a method for RAII-guarding fields in, which works even if an iDisposable object is created in a initializer or base-class constructor but an exception is thrown before the deepest derived class' constructor completes. The approach would probably work with iDisposables created by the constructor in C#, but not for initializers, since the creators of C# decided to run initializers before constructors (catering to the unusual situation of a constructor calling a virtual method, rather than the scenario of an initializer wanting to define values in terms of the constructed base base object).
The object uses a protected constructor which accepts as a parameter a list of iDisposable. The constructor is invoked by a static factory method which creates the list and passes it to the constructor. The creation of any iDisposable created during construction will be wrapped in an RAII method (which in C# would look something like:
T RAII<T>(T thing) {
  return thing;
In VB, such wrappers could be applied to initializations that occur when objects are declared (e.g.
  Dim MyBitmap As RAII(New Bitmap(320,240))
but in C# they would only work for initializations within the constructor.
Anyway, the RAII method seems nice as a technique for handling fields that will only be written once, during object construction, and which represent "owned" iDisposable objects. Given a list of iDisposable objects, cleanup is basically a matter of disposing of everything on the list; this can occur either within the object's Dispose method, or in the factory method if an exception is thrown during construction.
GeneralMy vote of 5 PinmemberJohn Brett28-Oct-10 6:21 
GeneralRe: My vote of 5 PinmemberRoberto Collina29-Oct-10 0:42 
GeneralRe: My vote of 5 PinmemberAndreas Gieriet29-Oct-10 1:53 
GeneralMy vote of 1 PinmemberJohn Simmons / outlaw programmer28-Oct-10 6:06 
GeneralRe: My vote of 1 PinmemberNemanja Trifunovic28-Oct-10 6:10 
GeneralRe: My vote of 1 PinmemberJohn Simmons / outlaw programmer28-Oct-10 7:17 
GeneralRe: My vote of 1 PinmemberNemanja Trifunovic28-Oct-10 7:50 
GeneralRe: My vote of 1 PinmemberAndreas Gieriet28-Oct-10 23:16 
GeneralRe: My vote of 1 PinmemberAndreas Gieriet28-Oct-10 23:23 
GeneralNice... PinmemberNemanja Trifunovic28-Oct-10 5:32 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.150302.1 | Last Updated 29 Oct 2010
Article Copyright 2010 by Andreas Gieriet
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid