The essence of my task is to come up with a situation when a finalizer is needed. I wanted to make an example with the file system. A reference to an instance of the FileStream class is passed to the class and, in theory, when removing my class, the stream should close. Here is my example: there is a class that in the constructor takes an instance of the FileStream class as an argument:
class MyClass { FileStream _fileStream; public MyClass(ref FileStream filestream) { this._fileStream = filestream; } ~MyClass() { Console.WriteLine("Object destroy."); _fileStream.Close(); _fileStream.Dispose(); _fileStream = null; GC.Collect(); } } The main program:
static void Main(string[] args) { var path = Directory.GetCurrentDirectory() + @"\..\..\folder\"; FileStream fileStream = new FileStream(path + "Text.txt", FileMode.OpenOrCreate); MyClass file = new ChildClass(fileStream); file = null; GC.Collect(); // fileStream.Close(); С этой строкой работает без исключения FileStream fileStream2 = new FileStream(path + "Text.txt", FileMode.OpenOrCreate); Console.ReadKey(); } When you create an instance of fileStream2 , an exception occurs stating that the file is occupied by another process. Why is the transfer of the link not working? Why is it that _fileStream and filestream are two different instances pointing to different links? The ref keyword is here as an experiment. After all, instances of reference types are passed by reference.
Console.WriteLine("Object destroy.");? - Grundy