Last active
January 15, 2026 21:44
-
-
Save sunmeat/8f64adf93662baf069e7f35fc78b9afd to your computer and use it in GitHub Desktop.
RAII C# example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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