c# object instantiation
Wha开发者_如何学运维t'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) ?
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
NullReferenceException
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.
There is no difference if you don't need the instance afterwards.
If you don't need o
afterwords then there is no difference.
The (JIT) compiler will probably treat them as being the same.
So it's a matter of taste. In this case I have a slight preference for the first one, but sometimes the fluent notation of the second sample is more readable.
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.
精彩评论