Click here to Skip to main content
15,121,540 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
C#
class Student
 {
     public int student_ID = 0;

     public string student_Fname = "";

     public string student_Lname = "";

     public string student_type = "";



     public Student()
     {

     }

     public Student(int ID)
         : this(ID , "", "")
     {

     }

     public Student(int ID, string Fname)
         : this(ID, Fname,"")
     {

     }
}


in the current code this keword when used as with constractor chainning refers to the current instance or to the parameter

What I have tried:

just read about it but think it is refer to the current parameter not to the current instance of the class
Posted
Updated 5-Aug-19 6:31am
Comments
Afzaal Ahmad Zeeshan 5-Aug-19 13:47pm
   
No, it does not target the current parameters, why would you think that? :-)

The keyword this always refers to the current instance of the enclosing class.

You have one constructor missing, so the code should be:
C#
class Student
 {
     public int student_ID = 0;
     public string student_Fname = "";
     public string student_Lname = "";
     public string student_type = "";

     public Student()
     {
     }

     public Student(int ID)
         : this(ID , "", "")  // call the final constructor that takes 3 parameters
     {
     }

     public Student(int ID, string Fname)
         : this(ID, Fname,"") // same as above
     {
     }
     public Student(int ID, string Fname, string Lname)
     {
         // set the values of the fields of the class.
         student_ID = ID;
         student_Fname = Fname;
         student_Lname = Lname;
     }
}

so the construct : this(ID, Fname,"") just calls the constructor with three parameters (the last one I added);
   
v2
Comments
Member 14479161 5-Aug-19 10:47am
   
hi thank you for the answer will you plese explain more according to the example here
Richard MacCutchan 5-Aug-19 15:00pm
   
See my updated solution.
This this specific case the this refers to overloads of the constructor of the instance. It's the equivelant of writing this code:
C#
public Student()
{
}

public Student(int ID)
{
    BuildIt(ID , "", "");
}

public Student(int ID, string Fname)
{
    BuildIt(ID, Fname, "");
}
   
Comments
Richard MacCutchan 5-Aug-19 14:53pm
   
BuildIt?
OriginalGriff 6-Aug-19 2:23am
   
A hypothetical method to use the parameters

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900