tags:

views:

358

answers:

4

I know I have done this before but I am getting my constructor order of execution in a twist I think....

public class Class1
{
    Class2 _class2;

    public Class1()
    {
        _class2 = new Class2(this);
    }
}

public class Class2 
{
    Class1 _parent; //corrected typo

    public Class2(Class1 parent)
    {
        _parent = parent;
    }
}

trouble is that parent always ends up null.

What's the proper way to do this? (maybe I can blame my slowness on having a cold..)

EDITED TO CORRECT THE TYPO (which isn't the problem in the real code!)

+2  A: 
Class1 parent;
_parent = parent;

_parent is never defined; you misspelled it.

geowa4
+11  A: 

You may have mistyped the code, but I think you want this definition for Class2 (notice the this qualifier in your Class2 constructor):

public class Class2 
{
    Class1 parent;

    public Class2(Class1 parent)
    {
        this.parent = parent;
    }
}
Keltex
Another win for "this"
annakata
If it were as simple as a typo its not likely to compile.
AnthonyWJones
+6  A: 

This should, technically, work, provided you change Class2 to include this.parent = parent;

However, I don't recommend this. I would, instead, recommend lazy initializing your class2 instance inside class1. Depending on what all is done in the constructor of Class2, you can potentially lead yourself into nasty situations.

Making a Class2 property on class1 and lazy initializing it would cause Class2 to be constructed after Class1's constructor is completed, not during it's construction, which is most likely less error prone if your classes get more complicated.

Reed Copsey
in the production code it is a property. thanks - thhis is how I havne it in the past....
kpollock
oh my - I really cannot type today, can I :-)
kpollock
+1  A: 

I don't see why this shouldn't work. It works with me.

declared: http://vvcap.net/db/I2OZoapbIRREvQ8ymPym.htp

stepped over: http://vvcap.net/db/ehsYqCY6JByqZQq-RXGp.htp

here's the result: http://vvcap.net/db/ZWjqb_Yv1yAisX0BYUns.htp

galets