Is it possible to refer to "this" in the constructor?

In C #, the general template that I use is to populate the details of the lower class of a computation with a form object.

Constructor for MyForm:

MyForm() { _MyFormCalcs = new MyFormCalcs(this); } 

But today I came across an error that makes me think that, since my constructor did not finish the completion, it creates a new instance of MyForm to be transferred to MyData. Thus, it calls the constructor twice. I found that the static list in MyFormCalcs was populated twice and not executed a second time, since the keys were already in the list.

Can this be used in the constructor to refer to this instance? What will it contain in the lower class - does the constructor work or not.

What is the best way to pass my form to lower class?

+6
constructor c # this winforms
source share
4 answers

No, this will not create a new instance of MyForm .

In general, allowing this to escape from the constructor is dangerous , as this means that it can be used until the constructor completes, but it will not create a new instance. If you could give a short but complete example of the problem you saw, we could help diagnose it further. In particular, it is unclear what you mean when a "static list is populated twice." It is generally not recommended to populate a static variable in the instance constructor.

+8
source share

In fact, it is very useful to avoid such a call inside the constructor, because your object has not yet been built (the constructor has not completed its work), but you are already using this "incomplete" object as a parameter. This is bad. A good way is to create a special method:

 class MyClass { var obj:SomeClass; public MyClass() { } public Init() { obj = SomeClass(this); } } 
+2
source share

Make a private property that creates an instance of MyFormCalcs only at first use, for example:

 public class MyForm { private MyFormCalcs MyFormCalcs { get { _MyFormCalcs = _MyFormCalcs ?? new MyFormCalcs(this); } } } 

This way, you don’t have to think about when to β€œinitialize” things.

+1
source share

There is a very complete C # constructor order reaction:

C # constructor execution order

0
source share

All Articles