Skip to content

Instantly share code, notes, and snippets.

@sunmeat
Last active January 15, 2026 21:44
Show Gist options
  • Select an option

  • Save sunmeat/8f64adf93662baf069e7f35fc78b9afd to your computer and use it in GitHub Desktop.

Select an option

Save sunmeat/8f64adf93662baf069e7f35fc78b9afd to your computer and use it in GitHub Desktop.
RAII C# example
using System.Text;
namespace FileResourceExample
{
class FileResource : IDisposable
{
private FileStream file;
public FileResource(string filePath)
{
file = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
}
public void Write(byte[] buffer, int offset, int count)
{
file.Write(buffer, offset, count);
}
public void Dispose()
{
file?.Dispose();
Console.WriteLine("Все гаразд!");
}
}
class Program
{
static void Main()
{
Console.OutputEncoding = Encoding.UTF8;
try
{
using (FileResource file = new FileResource("file.txt"))
{
// працюємо з ресурсом
byte[] data = { 72, 101, 108, 108, 111 }; // "Hello" в байтах
file.Write(data, 0, data.Length);
}
// ресурс буде звільнений при виході з блоку using
}
catch (Exception)
{
Environment.Exit(0);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment