Would you always create a variable for new objects?

.net

Solution

As you describe it, there is no effective difference between the two alternatives. But if you often need to create an instance of an object, just to call a single method; you should consider if your design is right ? Is it neccessary to have all these short-lived objects ? Remember, that for each object allocation, the garbage collector eventually has to collect the reference.

Problem

A question I often ask myself, if you need to call one method on an object, is it best practice to use a variable? Thus far I've guessed the answer is Yes - what's your choice, and reasons for it? With variable: ``` MyObject mo = new MyObject(); mo.MyMethod(); //mo not used again ``` Without variable: ``` new MyObject().MyMethod(); ``` I'm particularly interested in .NET, however if there are any danger points in other languages I'd also prefer to be forewarned.

Original source