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){
  • 2
    In both of your examples, you're doing work outside of the constructor, not inside it. Oct 5 '20 at 15:47

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.