Why can I create an instance of a class without storing it in a variable and still work?

I have a non-static class called ImplementHeaderButtons that contains a non-static public method called Implement . The name of the class and method is not important, the important thing is that they are not static, so they need to be created for use, right?

So I did this:

 var implementHeaderButtons = new ImplementHeaderButtons(); implementHeaderButtons.Implement(this, headerButtons); 

But then I decided to play a little with him (in fact, I was looking for a way to make it one liner), and I came to the conclusion that the following code works just as well:

 new ImplementHeaderButtons().Implement(this, headerButtons); 

Now I do not need a variable to store the instance, but my question is: how can I create a new instance of the class on the fly and call its method without saving the instance variable?

I would not be surprised if it does not work as intended, but it is.

+2
source share
3 answers

they are not static, so they need to be created for use, right?

Yes, but you are still creating an instance of the class with new ImplementHeaderButtons() , you just do not keep the reference to this newly created instance somewhere.

You can still call the method on this instance, as you did in your example, but after that you can’t do anything with it without a link. In the end, the instance will be cleared by the garbage collector (unless the called method stores an object reference somewhere).

+7
source

A variable is just a reference, for your convenience. You do not call it, but it is just there, on the top of the stack (in general ;-)). You can call its methods as long as you can reference the variable, either using its name (which you don’t have) or working on the “unnamed” object you just created.

0
source

Your call to new ImplementHeaderButtons() returns an instance of the ImplementHeaderButtons instances. Then you call .Implement() on this instance.

Think of it this way:

 (new ImplementHeaderButtons()).Implement(this, headerButtons); 
0
source

Source: https://habr.com/ru/post/1241508/


All Articles