+ 1

Destructor

How can I tell when the program(object) ends, so that the destructor comes in action?

21st Mar 2017, 6:19 PM
Amir Hossein Karimi
Amir Hossein Karimi - avatar
6 Respuestas
+ 14
Deleting means whatever the object is storing is erased, and it cannot be used anymore (since it doesn't exist). The memory it takes up is cleared. It's automatically done to free up memory. Objects are deleted even if you don't make your own destructor. Destructors you make yourself are meant to do some action (Ex: Write to a log file, close a file/database, etc.) If you make an object in a method, it cannot be called outside of the method. That's all its "lifespan" lasts for. And when that lifespan ends, the object is deleted. Ex: void doStuff(string x, int y) { User userObj = new User(); //Instantiation //some code } //Destruction - userObj only exists in doStuff(), and is deleted here
21st Mar 2017, 7:11 PM
Tamra
Tamra - avatar
+ 14
yw, glad to help :3 The destructor in this case will run after WriteLine(). The object C will last throughout all of Main(). So it's deleted after the code hits the } at the end of Main().
21st Mar 2017, 7:32 PM
Tamra
Tamra - avatar
+ 12
A destructor runs once an object is completely done being used. Ex: If you instantiate an object in a method, that object is deleted (and the destructor runs) when that method ends.
21st Mar 2017, 6:54 PM
Tamra
Tamra - avatar
+ 2
thank u Tamra. you really helped a lot 😊
21st Mar 2017, 7:37 PM
Amir Hossein Karimi
Amir Hossein Karimi - avatar
+ 1
that is exactly my problem. I dunno WHEN and HOW an object is deleted. never saw an direct example on this issue.
21st Mar 2017, 6:57 PM
Amir Hossein Karimi
Amir Hossein Karimi - avatar
+ 1
Tamra thank u so much for your extedended explanation and endurance to respond. but here is the real thing that is slightly bothering me. see this code: static void Main(string[] args) { Someclass C = new Someclass(); Console.Writeline("something"); } Is the destructor executed 1.before 2.during 3.after the moment which "Console.Writ..." is executed?
21st Mar 2017, 7:26 PM
Amir Hossein Karimi
Amir Hossein Karimi - avatar