What is "this" in object constructors?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mrjohn
    New Member
    • May 2009
    • 31

    What is "this" in object constructors?

    Hullo, I've been learning C# and I had a question. I'm creating a class, and I was writing the constructor. When I was assigning values to it's variables, I found that the compiler seems to take it both with and without the "this" keyword. Does it make a difference whether I use it or not?

    [CODE=C#]public class Car
    {
    private float weight, gasTank;
    public Car(float myWeight, float myGasTank)
    {
    this.weight = myWeight;
    this.gasTank = myGasTank;
    }[/CODE]
  • tlhintoq
    Recognized Expert Specialist
    • Mar 2008
    • 3532

    #2
    Nope. No difference. this. is merely specifying the scope.

    In theory you could have a "weight" in one class, and a "weight" in another class. You would want to be clear about which one you mean.

    class1.weight
    class2.weight

    In this case when the search starts to find a 'weight' the only one is the one in .this

    Comment

    • mrjohn
      New Member
      • May 2009
      • 31

      #3
      Cool beans. Thanks.

      Comment

      • artov
        New Member
        • Jul 2008
        • 40

        #4
        It is quite common to use same name for object's instances and parameters in constructors, like

        Code:
        public class Appointment
        {
           float duration;
           string name;
           DateTime time;
        
           public Appointment(string name, DateTime time, float duration)
           {
              this.name = name;
              this.time = time;
              this.duration = duration;
           }
        ..
        }
        This make the code easier to read and if you use environment like Visual Studio or SharpDevelop, it is easier to select the right constructor, if there are several.

        Comment

        Working...