To understand how this C# dispose works, I have created a class called Student and implemented IDisposable. This is my code
class Student: IDisposable
{
private bool disposedValue;
public int id { get; set; }
public string name { get; set; }
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
// TODO: dispose managed state (managed objects)
}
// TODO: free unmanaged resources (unmanaged objects) and override finalizer
// TODO: set large fields to null
disposedValue = true;
}
}
public void Dispose()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
How do I know above code is actually disposed my object? because once I call dispose method then also I can able to access my object properties?
public static void Main()
{
CreateStudentClass();
}
static void CreateStudentClass()
{
Student s = new Student();
s.Dispose();
Console.WriteLine(s.name); // I can able to access object properties.
}
When will Garbage Collection reclaim the memory of my student object s? I know above code is managed code and GC will automatically reclaim its memory once its out of scope of the method that I used for creating the object.
What is the use of Dispose method? because there is no implementation in it and in all the youtube videos and blogs also this is how they have implemented the Dispose method.
If my above code is wrong, let me know how to properly dispose my student object. Thanks in advance.
The Dispose method is designed to be called when you want to release resources that your object is holding, such as unmanaged resources like file handles or database connections.
To dispose of a Student object, you should add code to the Dispose(bool disposing) method to release any resources that the object is holding. For example a file handle.
class Student: IDisposable
{
private bool disposedValue;
private FileStream fileStream;
public int id { get; set; }
public string name { get; set; }
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
// Dispose of managed resources
fileStream?.Dispose();
}
// Dispose of unmanaged resources
fileStream = null;
disposedValue = true;
}
}
public void Dispose()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
//etc...
}