Is it okay to do
new Class().Methodname()
when I don't need the object anymore, or is it better to do
var class = new Class();
class.Methodname();
Is it okay to do
new Class().Methodname()
when I don't need the object anymore, or is it better to do
var class = new Class();
class.Methodname();
Is it okay to do
Well, that depends. Your program will work either way and the generated IL is (basically) identical when compiled for release. The question is, why is that method not static
if it's apparently not dependent on any actual state of Class
?
Generally, it's at least a good indication that the class is not modelled correctly if you find yourself creating a new instance and abandoning it directly afterwards only because you needed to call a method on it.
void Main()
{
var x = new MyClass().Do();
var z = new MyClass();
var y = z.Do();
}
public class MyClass
{
public string Do() => "hello";
}
Compiled under Release
configuration, this results in the following IL:
IL_0000: newobj UserQuery+MyClass..ctor
IL_0005: call UserQuery+MyClass.Do
IL_000A: pop
IL_000B: newobj UserQuery+MyClass..ctor
IL_0010: callvirt UserQuery+MyClass.Do
IL_0015: pop
IL_0016: ret
MyClass.Do:
IL_0000: ldstr "hello"
IL_0005: ret
MyClass..ctor:
IL_0000: ldarg.0
IL_0001: call System.Object..ctor
IL_0006: ret
For more information on the difference (call
vs. callvirt
), see e. g. this question.
I don't see much difference in between two approaches when it comes to performance .
Second approach gives you more readability and maintainability
It depends. Like germi says it indicates a design flaw. But further, if the class implements idisposable you should be using it in the context of a try finally block or using:
using(var class = new Class())
{
class.Methodname();
}
to make sure it is disposed and any resources it holds are released.