C# and destructor calling | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

C# and destructor calling

I am trying to understand a new challenge that I came across... I am putting the code below, well I have added a couple of things and made it extremely generic for this question... it won't execute for the obvious reasons.. class Class { public void class() { x statements; } ~Class() { y statements; } } static void Main(string[] args) { 1 new Class(); 2 Class history = new Class(); 3 history.class(); } So in Main.. if there is only line 1 in main, it goes straight to the Class destructor skipping class and executes the y statements....but I am assuming this is because class is not being called. However, if I have all three lines, it calls to class and executes x statements, then it executes y statements twice. Wouldn't it execute y statements, then x statements then go back and finish out with y statements again?

16th Feb 2019, 9:29 PM
laura
2 Answers
+ 3
It is very dangerous to call you example Class C# is case-sensitive so it should be possible in theory, but it is really confusing Please have a look at my sample code. https://code.sololearn.com/c0eedplr31Ff A constructor is a special method that has the name of the class. Here is where case-sentive confusing comes in The name of you constructor should be : Class And it should not have a return type not even void : public Class() but please use class SampleClass { public SampleClass() In your main 1 new Class(); Does create a instance of your Class, but since it is not assinged to a variable. It is use less. 2 this is the line where you call the constructor because you a creating a instance of the object. You cannot call the constructor itself. 3 In this line you have a standard method call, this is not the constructor
17th Feb 2019, 8:28 PM
sneeze
sneeze - avatar
+ 1
@sneeze thank you for taking the time to look at this. maybe I made this way too generic. I agree that class would not be a wise name... sorry for the confusion. I was trying to understand. . the destructor from what was in the challenge question.. as I got the answer wrong.. and I didn't want to post the verbatim quiz question here. When I walked through it on my computer.. it didn't fully make sense.. as I know the garbage collector. .. handles this. thanks again. :)
18th Feb 2019, 2:22 AM
laura