tags:

views:

127

answers:

4

What's the difference between:

Object o = new Object();
o.foo();

and

new Object().foo();

(assuming I do not need the reference afterwards) ?

Are there any reasons for using one instead of the other one (e.g. memory usage) ?

+6  A: 

There is no difference if you don't need the instance afterwards.

trendl
A: 

No difference.

To probe it, you can compile both codes (release mode), inspect them with ildasm and you will see the resulting bytecode witll be the same.

EDIT: actually, I sometimes find it easier to debug when the variable is declared. Easier to inspect, so, easier to debug.

Daniel Dolz
A: 

EDIT: Removed incorrect code

The difference is that in the first case you can see the object being created in the debugger.

Daniel Rose
and you can reuse it.
Femaref
@Femaref: what ?
user1112111
@Daniel Rose: actually that won't compile as well, a cast should be made for a class that has the `foo` method, but thanks for the answer
user1112111
@Daniel: Why would you need to do that? Those parentheses are unnecessary.
Jon Skeet
@user1112111: I reused your code. Obviously Object() doesn't have a foo Method. @Jon Skeet: You are right. My bad.
Daniel Rose
+7  A: 

There's no difference in terms of execution.

There can be a difference in terms of debugging:

  • It can be handy to break after the object has been created but before foo() is called
  • It can be handy to be able to inspect the value of the variable afterwards
  • If an exception is thrown, separating calls into multiple lines can make the source clearer. (I don't think it would be a problem in this particular case, but for NullReferenceExceptions in particular, it can be tricky if there are multiple dereferencing operations in the same statement).

I'm definitely not saying that you should always split everything out - just that it can be useful for debugging purposes.

Jon Skeet
Mr. Skeet, you strike again!
user1112111
Another difference is that - once declared - you can't reuse the variable name o again in the same scope. Probably a moot point, but a difference nonetheless.
Jono
@Jono, think that by scope you really mean declaration space. http://blogs.msdn.com/ericlippert/archive/2009/08/03/what-s-the-difference-part-two-scope-vs-declaration-space-vs-lifetime.aspx
Fede
@Fede, I'm only parroting back the compiler error that would follow: A local variable named 'o' is already declared in this scope. And we start to drift off topic...
Jono