Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In C#, a common pattern that I use is to populate the details of a lower calculation class with a form object.

The constructor for MyForm is:

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

But I encountered an error today which makes me think that as my constructor had not finished completing, it creates a new instance of MyForm to pass into MyData. Thus it calls the constructor twice. I found that a static list in MyFormCalcs was being filled twice and was failing the second time as the keys were already present in the list.

Can I use this in the constructor to refer to this instance? What will it contain in the lower class - has the constructor been run or not.

What is a better way of passing my form into the lower class?

like image 977
Peter Avatar asked Feb 23 '11 07:02

Peter


People also ask

Can you use this in constructor?

Using this with a Constructor From within a constructor, you can also use the this keyword to call another constructor in the same class.

Can I use this in constructor C#?

The “this” keyword in C# is used to refer to the current instance of the class. It is also used to differentiate between the method parameters and class fields if they both have the same name. Another usage of “this” keyword is to call another constructor from a constructor in the same class.

What can I use instead of this in Java?

'this' means 'current object'. In static methods there is no current object. In your example, try replacing this with new Main() .

When should we use this in Java?

The this keyword refers to the current object in a method or constructor. The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter).


2 Answers

No, that won't create a new instance of MyForm.

In general, allowing this to "escape" from a constructor is dangerous as it means it can be used before the constructor has completed, but it's not going to be creating a new instance. If you could give a short but complete example of the problem you've seen, we could help diagnose it further. In particular, it's not clear what you mean about the "static list being filled twice". Usually it's not a good idea to populate a static variable in an instance constructor.

like image 124
Jon Skeet Avatar answered Oct 22 '22 22:10

Jon Skeet


In fact, it is really nice to avoid such call inside constructor, because your object is not already built (constructor hasnt finish its work) but you are already use this "unfinished" object as a parameter. Its a bad way. Good way is creating some special method:

class MyClass
{

 var obj:SomeClass;

  public MyClass()
  {
  }

  public Init()
  {
    obj = SomeClass(this);
  }

}
like image 24
Alexander Sobolev Avatar answered Oct 22 '22 20:10

Alexander Sobolev