Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad practice to instantiate a class on the same line that you call a method on it?

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)?

like image 856
lintmouse Avatar asked Dec 05 '12 16:12

lintmouse


People also ask

What happens when a class is instantiated?

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.

What kind of class can you instantiate?

all classes can be instantiated except abstract. but you can create a reference variable of abstract class type.


2 Answers

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.

like image 155
Jens Neubauer Avatar answered Oct 01 '22 09:10

Jens Neubauer


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?

like image 40
bobble14988 Avatar answered Oct 01 '22 08:10

bobble14988