Who calls Dispose in .NET and how Finalization works in .NET
Dispose Myth's - Two Questions
Read the below code to answer the questions that follow the code.
PrintFileContent();
Console.ReadKey();
static void PrintFileContent()
{
//Notice that I have not wrapped the DisposableStream object in a using block and neither I am calling Dispose method.
var disposableStream = new DisposableStream("file");//Assume that file exists in the current directory.
disposableStream.PrintAllLines();
Console.WriteLine("I am done with the stream.");
}
public class DisposableStream(string fileName) : IDisposable
{
private readonly FileStream _fileStream = new(fileName, FileMode.Open);
public void PrintAllLines()
{
using var streamReader = new StreamReader(_fileStream);
while (streamReader.ReadLine() is { } line)
{
Console.WriteLine(line);
}
}
public void Dispose()
{
_fileStream.Dispose();
Console.WriteLine("DisposableStream dispose was called");
}
}
- Will the
Disposemethod be called on theDisposableStreamobject when thePrintFileContentmethod completes, since we are not wrapping it in ausingblock and neither calling theDisposemethod explicitly? - If the
Disposemethod is not called, how will theFileStreamobject be collected by the Runtime?