In C#, the memory is allocated by dynamically at Runtime and don’t have to explicitly allocate memory. So you don’t need to worry about allocate memory and then reclaim it. It is done for you at backend by Garbage Collector process. CLR periodically checks memory heap. It looks for unreferenced objects and releases resources. And then that memory can used for other purpose. So that constant cycle can be going on in an application. That whole process is known as Garbage Collection.
Here’s the lifetime of an object and how it works with garbage collection;
Let say when you declare a variable but you don’t provide it with a reference object. At this time, no memory in the memory heap is been used. We’ve created a pointer but it’s not pointing to anything.
When you instantiate an object and pointed at the variable, now there’s an object in the memory and it is reference by a variable. Perhaps this object is not eligible for the garbage collection.
But then let say you set the object to Null.
That doesn’t immediately destroy the object in the memory but it does dereference it. So that object is now eligible for the garbage collection. The Garbage object can find all such object, release its memory and make the memory available for the future use.
Perhaps when you create an object for Windows or UWP, these apps run on the windows run time or WinRT which is the native environment, not a managed environment. But! The .Net framework is integrated as the sub-form of WinRT. When you program in C# for WinRT, your WinRT object is managed by reference counting not be garbage collector. Many of the WinRT objects you might create are really just thin rappers, or what are known as projection to .NET Framework object. The WinRT objects might not be taking much memory at all. The real work might be done at the background by the .NET framework. But all you need as programmer is the memory management is automatic! Your .NET objects which are reference by the WinRT objects are still subject to garbage collection! If you’re building Windows or UWP apps with C#, you still don’t have to manage memory directly. But that tell you that that understanding that go on under the convers with your C# Apps can be very useful, especially when the Apps grow in size and complexity. Understanding how the objects are managed in C# based Apps can help you to build very memory efficient Apps!