-2

I'm a novice of programming who's learning C# recently.

When reading my textbook, I see the code below:

public class Panda
    {
        public Panda Mate;
            
        public void Marry(Panda partner)
        {
            Mate = partner;
            partner.Mate = this;
        }
    }

The book says that this here is used to set the mate field of partner, but I don't know what does that mean.

I'll be a big help if someone can explain it to me.

Mr. XP
  • 9
  • 4
    It's a reference to the current instance of `Panda`. If you access `partner.Mate`, that will be the same object as `this` – canton7 May 17 '21 at 16:22

1 Answers1

2

"this" Panda gets married to the Partner supplied as parameter to the Marry method. So, the Mate of the Partner is this Panda.

"this" Panda's Mate is the Partner. The Partner's Mate is this Panda. They are connected vice-versa.

Technically, "this" in this case is a pointer to itself set as Mate on the Partner's Panda instance.

Grisgram
  • 3,105
  • 3
  • 25
  • 42