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) ?
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) ?
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.
EDIT: Removed incorrect code
The difference is that in the first case you can see the object being created in the debugger.
There's no difference in terms of execution.
There can be a difference in terms of debugging:
foo()
is calledNullReferenceException
s 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.