views:

96

answers:

4

Example 1:

SomeObject someObject = new SomeObject();
if (someObject.Method())
{
    //do stuff
}
//someObject is never used again

vs

Example 2:

if (new SomeObject().Method())
{
    //do stuff
}

Is there any benefit to using the first method over the second, or vice versa?

+2  A: 

Can be useful while debugging to be able to see the value (and if the object was something in COM interop or similar that you'd need to dispose of it might be important to keep the reference so you are able to do so in a controlled manner).

If the names are long or if there are multiple levels of nesting it can also be easier to read.

ho1
+11  A: 

There are at least three potential benefits:

  1. Readability: the first is more obvious in many cases than the syntax of the second example, especially to newer developers.

  2. Better debugging experience: If the constructor for SomeObject throws an exception, in the first case, the debugger will break on that line. In the second case, it's not obvious whether the exception is in the constructor or the method. The same issue arises for setting break points and inspecting values on the object - this will be difficult in the second case, and require setting the break point inside of the method.

  3. In the first case, you can use the object outside of that single call. If you really only need a method for a single call, and don't need the object reference, then a static method may be more appropriate.

Reed Copsey
Excellent points. Thanks!
user4123
+2  A: 

In most trivial cases, the compiler will remove it anyway. There is an important point with value-types, which is that copying it into a variable clones the value, so can represent a significant change - but you shouldn't encourage mutable value-types anyway.

With floating-point, there are some edge-cases where when it uses a local you get different answers (the native types have greater width than Single / Double etc) - which also means you can get different results with debug/release (depending on whether the variable is removed by the compiler).

There are also cases where the variable can do more than the value on the stack - i.e. be "captured" into a lambda / anon-method, or be used for out/ref, but that rarely applies.

Marc Gravell
A: 

I'd favor the first option for improved readability, e.g.:

var phoneNumberRx = new Regex(@"^\(\d{3}\)\d{3}-\d{4}$");
Jordão