Question

This is very closely linked to the question Legitimate "real work" in a constructor? but not quite the same.

I am interested in having feedback on whether this is acceptable or has any risks. in C#, I instantiate a class:

var f = new Foo(DoSlowComplexTask());

it seems the same as doing:

var x = DoSlowComplexTask();
var f = new Foo(x);

NOTE: this is a bit different from the often asked question where we have

public class Foo{
   object workResult;
   public Foo(object someParam){
   DoSlowComplexTask(someParam);
  }
}
Was it helpful?

Solution

If you want to use the result of DoSlowComplexTask outside the instance of Foo, sure, assigning the result to the x variable is a good idea, so that the result is ready. Otherwise the two approaches are the same, smart compiler will likely even produce the same machine code, and both of the approaches are fine.

Licensed under: CC-BY-SA with attribution
scroll top