Search code examples
c#declarationthrowaway

Should I fully declare throw-away objects?


If I need to do something like this:

var connection = new Connection(host);
connection.Execute(Commands.Delete);

Is there anything wrong in doing this:

(new Connection(host)).Execute(Commands.Delete);

The first example may be more readable, but the second works better if I need to do this multiple times:

(new Connection(anotherHost)).Execute(Commands.Create);
(new Connection(someOtherHost)).Execute(Commands.Update);
(new Connection(host)).Execute(Commands.Delete);

Solution

  • First thing I am a Java person and I havent used C# But based on your code and knowing similarity with java what I can say is -

    If your Connection class maintains a state information then its meaningful to create new object every time. But if it is stateless then its pretty inefficient to create multiple objects. You can create one and re-use the same.

    i.e. If you cannot set the 'host' to a connection once created, then both approaches you mentioned should not make any difference.