Javed Akram
Javed Akram

Reputation: 15354

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
}

Upvotes: 2

Views: 2017

Answers (4)

Piotr Justyna
Piotr Justyna

Reputation: 4996

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.

Upvotes: 0

Kobi
Kobi

Reputation: 138147

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.

Upvotes: 1

Gareth McCaughan
Gareth McCaughan

Reputation: 19981

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 :-).

Upvotes: 1

RoflcoptrException
RoflcoptrException

Reputation: 52247

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.

Upvotes: 2

Related Questions