2

I have the following issue:

public class ChildClass{
   public Object Parent = null;
}
public class ParentClass{
   public ChildClass CreateChild(){
        return new ChildClass{ Parent = this; }
   }
}

I got a bit stuck understanding object initializers. In the CreateChild() method, does this refer to ParentClass or ChildClass?

0

3 Answers 3

5

this will refer the the class it is in.

In the example, this will be an instance of ParentClass, since it is declared within the body of ParentClass.

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks for the answer, but isn't this belong to ChildClass in this case as it is inside its inializer?
@GETah - No it doesn't. The object initializer is still within the ParentClass body.
@GETah, the initializer is shorthand to make your life somewhat easier and it isn't occuring inside the object being created. But step through the code, then you'll know.
No. How would you be able to pass the current instance of ParentClass to the new ChildClass object if it behaved like that. Only inside the ChildClass this refers to ChildClass. var c = new ChildClass{ Parent = this }; is the same as var c = new ChildClass(); c.Parent = this;
The object initializer is NOT within ChildClass but within ParentClass. Therfore this refers to the current instance of ParentClass. The object initializer does NOT belong to ChildClass but is a code which belongs to the method CreateChild of ParentClass. Everything which is between "public class ParentClass{" and the final "}" belongs to ParentClass.
|
1

To the instance of the ParentClass on which the CreateChild is executed (Though in its current way your code probably wont compile). this = the instance of the current class, which in this case is the parentclass

1 Comment

It does compile, the Parent member variable can be anything that is why it is of type Object
1

It refers always to the class where it is textually imbedded. In this case to ParentClass.


UPDATE

The object initializer is NOT within ChildClass but within ParentClass. Therfore this refers to the current instance of ParentClass. The object initializer does NOT belong to ChildClass but is a code which belongs to the method CreateChild of ParentClass. Everything which is between "public class ParentClass{" and the final "}" belongs to ParentClass.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.