0
class Perl
{
   private int value;

   public Perl()
   {
      this.value++;
   }

   public void display()
   {
      Console.WriteLine("B called: " + this.value);
   }
}

namespace ConsoleApplication1
{
   class Program
   {
      static void Main(string[] args)
      {
         Perl perl1=new Perl()
         perl1.display();

         Perl perl2=new Perl()
         perl2.display();
      }
   }
}

So I have been reading tutorial on "this" here and there trying out example codes and see what happens when I take out "this" from variables. From my understanding, "this" is a reference to an object (instance of a class) such as perl1 and perl2 in the code.

When I took out "this" from "this.value++" and "this.value", "value" and "this.value" remained the same. Is "this" even needed in this case since perl1 and perl2 are instantiated and have their own variables? (perl1's value and perl2's value are separate right?) If that's the case, why is "this" even needed or used since all the variables belong to the separate objects?

I want to start using "this", but every time I try to learn about it, the more confused I get.

Would someone explain this to me?

n0bod1
  • 255
  • 1
  • 2
  • 13
  • simple answer `this` denotes the current instance – sujith karivelil Apr 28 '16 at 15:38
  • do you know happen if you write value++ without this? – Arsen Mkrtchyan Apr 28 '16 at 15:40
  • 1
    [When do you use the “this” keyword?](http://stackoverflow.com/questions/23250/when-do-you-use-the-this-keyword) – Steve Apr 28 '16 at 15:41
  • if I write value++ without this, the value stays the same right? – n0bod1 Apr 28 '16 at 15:44
  • @user2521723 - no, in your context it does not matter have you used `this` or not. it always will increment the value. – MaKCbIMKo Apr 28 '16 at 15:47
  • `this` is implied so long as there's not a local variable of the same name. The reason it doesn't _seem_ to change is that putting `++` _after_ the variable gives you the value of the variable _before_ the increment. – D Stanley Apr 28 '16 at 15:48
  • @MaKCbIMKo do you have a sample code that utilizes this effectively? – n0bod1 Apr 28 '16 at 15:53
  • Let's say that you have the following class: class Perl { public int value; public Perl(int value) { value++; // 1 value=value; // 2 this.value=value; // 3 } } In #1 and #2 - can you say what will happen? which variable will be used? But in #3 case it's pretty clear - it will take the passed parameter and saved to object field (`this` explicitly shows that) – MaKCbIMKo Apr 28 '16 at 16:05

0 Answers0