CSharp - Type Creation this Reference

Introduction

this keyword refers to the instance itself.

this reference is valid only within nonstatic members of a class or struct.

In the following example, the MakeFriend method uses this to set the partner's mate field:

class Person
{
       public Person Friend;

       public void MakeFriend (Person partner)
       {
           Friend = partner;
           partner.Friend = this;
       }
}

this reference disambiguates a local variable or parameter from a field.

For example:


class Test
{
       string name;
       
       public Test (string name) { 
          this.name = name; 
       }
}

Exercise