If I only need to instantiate a class to call a single method on it and then be done with it, I like to do it in a single line like so,
string result = new MyClass().GetResult();
Instead of doing something like,
var myClass = new MyClass();
string result = myClass.GetResult();
It is my understanding that the same thing is going on behind the scenes in terms of memory allocation and subsequent cleanup. Is this really the case or is there a difference? And if so, is one more efficient than the other?
EDIT:
Making the method static, like many of you have suggested, is a good solution. I am working with a class that someone else created that I am unable to refactor or change at the moment. So for this kind of situation, is there any difference in instantiating inline or on a separate line?
EDIT:
Does the answer to this question vary depending on the number of resources that the class maintains (from Blam & BenCr’s comments below)?
It should actually be more efficient to use the one-liner, since the runtime has one less local variable to keep track of for purposes of garbage collection.Edit: Incorrect, see Adam’s reply below. My original point still stands, tough, the effect (if any) should be negligible.But the real question is: Why is GetResult() not a static function? That would avoid the whole instantiation completely.