Explicitly use the reference to 'this'. - CSharp Custom Type

CSharp examples for Custom Type:this

Description

Explicitly use the reference to 'this'.

Demo Code

using System;//  w  w w  . j a v  a2 s  .c o  m
public class Program
{
   public static void Main(string[] strings)
   {
      Student student = new Student();
      student.Init("S Davis", 1234);
      student.Enroll("Biology 101");
      student.DisplayCourse();
   }
}
public class Student
{
   public string _name;  // Note this naming convention for
   public int _id;       // class data members.
   CourseInstance myCourse;  // Convention is optional.
   public void Init(string name, int id)
   {
      this._name = name; // With the naming convention, _name,
      this._id = id;     // 'this' is no longer needed.
      myCourse = null;
   }
   public void Enroll(string courseID)
   {
      myCourse = new CourseInstance();
      myCourse.Init(this, courseID);
   }
   public void DisplayCourse()
   {
      Console.WriteLine(_name);
      myCourse.Display();
   }
}
public class CourseInstance
{
   public Student _student;
   public string _courseID;
   public void Init(Student student, string courseID)
   {
      _student = student;   // 'this' not needed.
      _courseID = courseID; // Names are distinct.
   }
   public void Display()
   {
      Console.WriteLine(_courseID);
   }
}

Result


Related Tutorials