Is it a bad practice to create an instance of a class on the same line that you call a method on it?

If I just need to create an instance of the class to call one method on it, and then do with it, I like to do it on one line, for example,

string result = new MyClass().GetResult(); 

Instead of doing something like

 var myClass = new MyClass(); string result = myClass.GetResult(); 

I understand that the same thing happens behind the scenes in terms of memory allocation and subsequent cleanup. Is this true or is there a difference? And if so, is it more effective than the other?

EDIT:

Creating a static method, as many of you have suggested, is a good solution. I am working with a class that someone else created that I cannot reorganize or change at the moment. So, for such a situation, is there any difference in creating an instance of a row or a single row?

EDIT:

Does the answer to this question depend on the amount of resources supported by the class (from the comments of Blam and BenCr below)?

+6
source share
3 answers

In fact, using a single-line interface should be more efficient, since the runtime has one smaller local variable to monitor for garbage collection. Edit: Wrong, see Adam below. My initial point is still standing, tough, the effect (if any) should be negligible.

But the real question is: why is GetResult () not a static function? This would completely eliminate the entire instance.

+4
source

I don't see anything regarding your question in C # coding rules.

My personal preference would be the last example you gave. I think this will improve the readability of your code.

However, if you create an instance of a class to get one value from it, it might be better to rethink how this class is designed. Probably your GetResult () method should be static?

+3
source

This only applies if the class implements IDisposable. If you are looking for the efficient use of a single method and execute it, then neither one nor the other.
MyClass () will not be deleted until it goes out of scope.

 using (myClass = new MyClass()) { string result = myClass.GetResult(); } 

using Statement (C # reference)

Consider static methods and classes.

Static classes and members of a static class (C # programming guide)

The garbage collection is a broad topic.
You stated that this is not your code, but if you are writing code containing resources, there are some recommendations.

IDisposable Interface

0
source

All Articles