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?
Using this with a Constructor From within a constructor, you can also use the this keyword to call another constructor in the same class.
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.
'this' means 'current object'. In static methods there is no current object. In your example, try replacing this with new Main() .
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).
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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With