MANAGED VS UNMANAGED RESOURCES
- Managed Resource – The objects that are created by CLR are called as “Managed Resources”
- These will participate in “Garbage Collection” process, which is part of .net framework.
- Unmanaged resources :- Objects that are not created by CLR are called unmanaged resources. Example – filestream, database connection
- Who will clear the unmanaged resources??
- Destructor – clears the unamanaged resources – generally at the end of application execution
- Special method of the class which is used to close unmanaged resources (such as database connections, file connections) that are opened during the class execution.
- ~className{ }
- Dispose – clears the unmanaged resources after the specific task is completed. No need to wait till the end of application execution.
- Destructor – clears the unamanaged resources – generally at the end of application execution
- Destructor:- We close those external connections so that there is no memory leakages.
- Destructor is public by default , we can’t change its access modifier.
- In IL it gets converted to finalize method
- Destructor doesn’t deallocate any memory, it just will be called by CLR (.net runtime engine) automatically just before the moment of deleting the object of the class.
IDISPOSABLE
- IDisposable has an interface called Dispose method which is used to close unmanaged objects.
PROGRAM.CS
using ConsoleApp25;
class Program
{
static void Main(string[] args)
{
Play();
Console.ReadKey();
}
public static void Play()
{
using (Cricket obj1 = new ())
{
obj1.Batting();
}
}
}
Cricket
namespace ConsoleApp25
{
public class Cricket :IDisposable
{
public void Dispose()
{
Console.WriteLine("Dispose method is called here");
}
public void Batting()
{
Console.WriteLine("Batting started !!");
}
}
}
OUTPUT
new method called !!
Dispose method is called here