Saturday, September 22, 2012

What is this (The meaning of (this) keyword) ?

As you have seen in the (In C# everything is object) post how the button object is created. You may have noticed that in the InitializeComponent() method to set a property of a button object it uses the this.button syntax. So what is the meaning of this this syntax? I know many of you guys don't know about it but always use it inside a method with objects or fields etc. Let me give an example. Maybe this will clear the concept.

1. Open the IDE.
2. Create a project.
3. Create a Class named Add.
4. Create two integer fields in this class.
5. I named them firstNumber & secondNumber.
6. Now create a method name AddTwoNumbers(int firstNumber,int secondNumber) which will return a integer type value which is just the addition of the firstNumber and secondNumber. Give the method  integer type parameters. The parameter should have the same name as the fields.
7. Now set up a UI. Containing two textBox for the first number and second number input, a button that will add the given number after its being pressed , and of couse a last TextBox to show the result of the addition.
8. Double click on the addButton and write the followings:
            Add addNumbers=new Add();
            int total=0;
            total = addNumbers.AddTwoNumbers(Convert.ToInt32(textBox1.Text),                            Convert.ToInt32(textBox2.Text));
            textBox3.Text = total.ToString();

9. Now go back to the Add Class and write this in the AddTwoNumbers(int firstNumber, int secondNumber)
            this.firstNumber = firstNumber;
            this.secondNumber = secondNumber;
            return this.firstNumber + this.secondNumber; 
10. Run the program and give two numbers and press add. tada!!! you just add two numbers
11. The main thing is here that my function parameter and my object fields both have the same names. So how will my compiler distinguish the difference of my object field and my parameters. Thats where the this keyword comes in and solve our problem. The thing is when you omit the this keyword from the beginning of the object fields you just set the value of the parameter to that parameter. Now tell me why the heck will you do that. That doesn't mean anything. So to strictly say that the parameter value will be assigned to the fields, you need to have the this keyword. The this keyword just say that (I want to deal with this object's fields, methods etc only). Otherwise at the debugging you will not see any errors. But due to the fact that the compiler doesn't distinguish between them it will just provide you with a wrong output. The this keyword has a very large effect when you compare two objects. So maybe I cleared the fact that why you use the this keyword. Later you will find more values of the this keyword.

No comments:

Post a Comment