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?
There are at least three potential benefits:
Readability: the first is more obvious in many cases than the syntax of the second example, especially to newer developers.
Better debugging experience: If the constructor for
SomeObjectthrows 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.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.