thisKeyword.md - brainchildservices/curriculum GitHub Wiki

Slide 1

‘this’ keyword in C#

In C#, ‘this’ keyword is used to refer to instance members of the current class from within an instance method or a constructor.In C#, ‘this’ pointer works only for nonstatic members of the class because ‘this’ works on the current instance and nonstatic members can be accessed by the instance of the class.

Slide 2

  1. To distinguish the method parameters from the class fields when they have the same name. Case1: We have a class Student with fields stuName and stuAge. We have a method Scan that has two parameters name and age which are stored to stuName and stuAge fields of the class. Then there is a Print method that print the student details. Everything works and there are no issues.
    https://dotnetfiddle.net/nZjQ8S
    Case2: The same situation as above except that the field names are name and age. Here the fields of the class and the parameters of the method have the same name.We get a warning message :"Assignment made to same variable.". And if we run the program we could see that the assignment operation was not done correctly and we don't get the output we intended to.
    https://dotnetfiddle.net/u7RnLN This is where we need the this keyword. We can add the "this." keyword to the field variable names: name and age to make sure that we are able to achieve what we need. That is to save the value of method parameter to the filed variables.
    https://dotnetfiddle.net/rya6pF

Slide 3

  1. To call the method in the same class We can use the this. keyword before a method when it is being called inside the another method of the same class. But the same works even without the this. keyword. But internally the compiler adds this keyword to the method even if we don't add it explicitly.
    https://dotnetfiddle.net/iWPAN3
    https://dotnetfiddle.net/5xt9m2

  2. Use ‘this’ keyword to call a constructor in the same class. : Constructor chaining
    We have two constructors for class Add: One with two parameter and the other with three parameter.
    We call the second constructor and pass the values.
    https://dotnetfiddle.net/8OjwXC
    We also have an option to call the first constructor inside the second constructor and do the same operation. This is achieved using this keyword https://dotnetfiddle.net/K4do76

  3. *Use of ‘this’ keyword is that we can use it to declare indexers. : Learn Indexers

References:
https://www.educba.com/this-keyword-in-c-sharp/
https://www.geeksforgeeks.org/c-sharp-this-keyword/
https://www.c-sharpcorner.com/UploadFile/puranindia/this-keyword-in-C-Sharp/
https://www.tutorialspoint.com/this-keyword-in-Chash
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/this
https://www.geeksforgeeks.org/constructor-chaining-java-examples/