User Tools

Site Tools


technical_notes:public:20131024-cs-raii-pattern

Parent

C# - RAII pattern (with using and IDisposable)

In C++, we use frequently the RAII pattern to manage Resources (in C++, memory is a Ressource.) and make the excepition management more easy using the destructor.

In C#, there is a way to do something equivalent with using statement :

using (StreamReader reader = new StreamReader("file.txt"))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
      string[] parts = line.Split(',');
    }
}

How to implement using block in C#

You have to implement the interface IDisposable on your class.

Ressources

technical_notes/public/20131024-cs-raii-pattern.txt · Last modified: 2013/10/24 14:05 by Fabien Arcellier