When I create an object/variable inside a method, after the method calls, all the objects will be set to be collected by GC and all “primitive” variables (int, string, decimal…) are destroyed, right?
So, if yes:
public void MyMethod()
{
// Imagine an class that connects with ftp server
MyObject o = new MyObject();
o.Connect();
}
If i have an error in the line o.Connect() and I have a try`catchonly to log the error,MyObject o` will be collected by GC?
There is no set time when the garbage collector does its "collecting." There are three "generations" of objects and objects are promoted up a generation if they survive collection. So yes, if you "catch" the error in a try/catch block then the garbage collector will free up the memory taken up by your object.
You can find out more about garbage collection here