We have two types in C#, those are Value Types and Reference Types. C# objects which are reference types do not have the same lifetimes as value types. When we create a C# object using new, it hangs around past the end of the scope. As shown below we can create the object for StringBuilder.
private void GetData()
{
StringBuilder sb = new StringBuilder();
sb.Append("This is String Builder Object");
}//end of scope for object sb
The reference sb vanishes at the end of the scope. However, the StringBuilder object that sb was pointing to is still occupying memory. In this bit of code, there is no way to access the object because the only reference to it is out of scope. Garbage Collector removes that object after specific predefined time.
In C++ we don’t get anything from language to make sure whether objects or available or not when we required them and you have to make sure that objects are destroyed after you are done with them.
Whereas in C#, .Net provides intelligence whether the objects are available or not and it take care about destroying the objects after some time even though we didn’t focus on destroying the objects. The .NET run-time has a garbage collector, which looks at all the objects and it identifies all objects which are not used in specific time. The objects which are not used in specific interval are destroyed by Garbage Collector. That means in C# you just focus on creating the objects and you no need to focus on destroying those objects, Garbage Collector will take care of those objects. This eliminates the certain Programming effort and issues like “memory leak”.