3

When referenced in the constructor, does the keyword this refer to the instance of the class being created?

For instance, I have a list of all instances of a certain class. If I put MyList.Add(this); at the end of the constructor, will that add the newly created class?

6
  • 3
    Out of interest if you are questioning this what other things did you think it might mean? Commented Dec 1, 2011 at 0:33
  • 1
    Also a class adding itself to a list in a constructor seems weird. It would mean you have a class that contains a list with itself in it. Bends my mind a little. Commented Dec 1, 2011 at 0:39
  • @BenRobinson The list doesn't necessarily have to be in the class itself (static, argument, etc). But yes, it does seem a bit odd. Commented Dec 1, 2011 at 0:51
  • @Rob either of those suggestions seems pretty odd too Commented Dec 1, 2011 at 0:57
  • 6
    @BenRobinson: That is not what it means. It means that the class is adding a reference to itself to a list that it contains a reference to. Imagine that you are the instance. You write your name on a piece of paper. You stick that piece of paper into a three-ring binder named "my notes". You write "my notes" on a piece of paper and put that in your pocket. Nothing weird about that. It's not you that is in the binder, it's just your name. It's not the binder that's in your pocket, it's just a piece of paper with the name of the binder on it in your pocket. Think in references. Commented Dec 1, 2011 at 3:37

4 Answers 4

12

Yes, it does.

Note that you are potentially exposing a partially-initialized instance of your class, which can be a bad idea.

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

1 Comment

As SLaks said, it is important to note the security issues of exposing this in this manner
9

Yes this refers to the current instance in the constructor just like in every other instance method.

Comments

1

Yes this refers current instance in the constructor

Comments

0

this always refers to the current instance, you can use this as a pointer to the instance

Comments

Your Answer

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