#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2014
    Posts
    2
    Rep Power
    0

    What is the logic behind the "this" keyword?


    Ok, I am having a hard time understanding the reasons behind the use of the keyword this.

    All the books and online references to this keyword only state that the this keyword is used to refer to the current instance of a given class. This statement makes sense on its face value, but it does not make logical sense to me when it comes to applying it to program execution.

    for instance, my understanding is that every time you create an instance of a class it creates the object in the heap and multiple instances of the same class gets its own place on the heap for each object. Now, every time you call a specific instance of the given class, the program is working only with that one instance at that time. so why do you have to use the this keyword?

    for instance look at this code:

    Code:
    class outputname {
    
    string name;
    
    public void printname(){
    
    Console.WriteLine("my name is {0}", name);
    
    }
    
    }
    
    outputname firstname = new outputname();
    firstname.name = "homersimpson";
    firstname.printname();
    
    outputname secondname = new outputname();
    secondname.name = "lisasimpson";
    secondname.printname();
    The code compiles and runs fine even without using the this keyword. This code displays the expected output without the use of the this keyword.

    when the program executes code related to the firstname object it only deals with that object in the heap and not the secondname object. In other words, each instance of the outputname class has its own place on the heap and the lines of code that assign the name values to each object only refer to that specific object on the heap. So why do you need to use the this keyword to tell computer to refer back to the object it is working on in the first place when it is only working on that object. Even if the computer works on multiple objects of the same class at the same time, the field assignment operations will be changed within each object respectively on the heap.

    They also say that you don't need to use the this keyword in a static method or static fields. Does not make sense to me at all. if I understood why the keyword this is used in the above context, I would understand this statement.

    lastly, interestingly enough, I came across the following code online and it demonstrates what can go wrong if you don't use the this keyword:

    Code:
      public class Demo
            {
                int age;
                string name;
     
                public Demo(int myage, string myname)
                {
                    age = myage;
                    name = myname; 
                }
     
                public void Show()
                {
                    Console.WriteLine("Your age is :"+age.ToString());
                    Console.WriteLine("Your name is : " + name);
                }
            }
     
            static void Main(string[] args)
            {
               
                Demo obj = new Demo(45, "Homer Simpson");
     
                obj.Show();
               
             }
    this outputs:

    Code:
    your age is: 0
    your name is:
    but if you add the key word this to the constructor like the following, the program works as expected:

    Code:
      public class Demo
            {
                int age;
                string name;
     
                // Have made change here included this keyword
                public Demo(int myage, string myname)
                {
                    this.age = myage;
                    this.name = myname; 
                }
     
                public void Show()
                {
                    Console.WriteLine("Your age is :"+age.ToString());
                    Console.WriteLine("Your name is : " + name);
                }
            }
     
            static void Main(string[] args)
            {
               
                Demo obj = new Demo(10, "Lisa Simpson");
     
                obj.Show();
               
             }
    output:

    Code:
    your age is: 10
    your name is: Lisa Simpson

    why do you need to use the this keyword here where as I did not need to use the this keyword in the first code example.

    Thanks in advance for the help.
  2. #2
  3. Wiser? Not exactly.
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    May 2001
    Location
    Bonita Springs, FL
    Posts
    5,938
    Rep Power
    4033
    Preface: I've not used .NET/C# in a long time, and was never well-versed in it, so the following may not be 100% technically accurate but fits my memory and observations


    Originally Posted by programmingfan
    for instance, my understanding is that every time you create an instance of a class it creates the object in the heap and multiple instances of the same class gets its own place on the heap for each object. Now, every time you call a specific instance of the given class, the program is working only with that one instance at that time. so why do you have to use the this keyword?
    You don't have to use this except in certain situations. As you've shown in your example, you can simply reference a variable/method and it works fine. Some reasons you may use the this keyword are:
    - To make it clear you are access an instance-level variable vs a local one
    - To resolve a name conflict
    - To reference the current object if necessary, such as when passing it as a parameter to a function.

    Originally Posted by programmingfan
    They also say that you don't need to use the this keyword in a static method or static fields. Does not make sense to me at all.
    Static fields and methods do not belong to or execute on any particular instance of an object. As such there is no instance which needs to be referenced making the this keyword irrelevant in these situations. Because it's irrelevant, it's considered an error to try and use this in such situations.

    Originally Posted by programmingfan
    lastly, interestingly enough, I came across the following code online and it demonstrates what can go wrong if you don't use the this keyword:
    I do not think you looked at this example properly. What you have written should work fine. This however, would fail as described:
    Code:
      public class Demo
            {
                int age;
                string name;
     
                public Demo(int age, string name)
                {
                    age = age;
                    name = name; 
                }
    The reason is that your age and name parameters override the instance-level variables of the same name. You can resolve this conflict and explicitly reference the instance-level variables by using the this keyword:
    Code:
    this.age = age;
    this.name = name;
    Last edited by kicken; January 25th, 2014 at 10:56 AM.
    Recycle your old CD's, don't just trash them



    If I helped you out, show some love with some reputation, or tip with Bitcoins to 1N645HfYf63UbcvxajLKiSKpYHAq2Zxud
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2014
    Posts
    2
    Rep Power
    0
    That makes a great deal sense. Thanks!

IMN logo majestic logo threadwatch logo seochat tools logo