2

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
}
1
  • 4
    You're creating an object in both cases (that's what new does). I don't understand the question. Commented Apr 6, 2011 at 9:20

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

Nitpick: p is a reference. There are actual pointers in C#, but this is not the case.
@Martinho - I'll take that. It's possible a "Pointer" is more recognizable. Thanks!
1

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.