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)?
Note: The phrase "instantiating a class" means the same thing as "creating an object." When you create an object, you are creating an "instance" of a class, therefore "instantiating" a class.
all classes can be instantiated except abstract. but you can create a reference variable of abstract class type.
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.
I can't see anything regarding your question in the C# coding conventions.
My personal preference would be the latter example you have given. I think that it would allow for improved readability of your code.
However, if you're instantiating a class just to get a single value from it, maybe it'd be better to rethink how that class is designed. Your GetResult() method should probably be static?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With