简体   繁体   中英

calling a function without creating object in C#

Is there any difference between these two cases in below program?

static void Main(string[] args)
{
     //Case 1:
     new Program().a();    

     //Case 2:
     Program p = new Program();
     p.a();
}

void a()
{
     // Do some stuff
}

In the first case you don't store you're Program object in a local variable. The function is executed, but you can access your object that called the operation anymore.

In the second case you store your object in a local variable and call again the method. The method is executed and you could access the same object again later.

So it depends what you're going to do. Concerning the executed method, there is no difference. You have to think about if you need the Program object once more anywhere else in your code. Then you have to store it in a variable. Otherwise you can do it like you did in your first case.

No. You're creating an object when you call new Program() . p is just a reference to that object, it adds almost nothing at all in terms of memory use or performances.

In terms of style and readability of your code, it is advisable to avoid statements like new Program().a(); - It makes the code harder to debug because you can't place a brake-point on the statement you want and can't tell what caused an exception you may have caused.
It is also not too clear what you're doing - you'd probably need to read that again to fully understand what is created , and what is executed and returned.

No. (Other than that the latter may be very slightly more convenient for debugging.)

I'm assuming here that the code above is all the code. Of course if you subsequently do something else with p then you've made a difference between the two :-).

There is just one difference (as you create a new object in both cases) - in the second one you can still access it by typing something like

p.AnotherMethod();

EDIT:

If you don't want to create an object to invoke method "a", make this method static .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM