Jump to content

issues comprehending ".this"

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
5 replies to this topic

#1
noxrawr

noxrawr

    Newbie

  • Members
  • PipPip
  • 23 posts
Alright, to avoid any confusion. I am fairly new to c # and therefor might be asking some silly questions but i suppose we all have to learn sooner or later.
From what I understood, .this refers to a field for example this.x = 1. If i misunderstand that please correct me.

Now i am following a book with an example code which I will post here.

#region Using directives


using System;

using System.Collections.Generic;

using System.Text;


#endregion


namespace Classes

{

    class Point

    {

        private static int objectCount = 0;

        public static int ObjectCount()

        {

            return objectCount;

        }

        [B]private int x, y;[/B]

        public Point()

        {

            this.x = -1;

            this.y = -1;

           

            objectCount++;

        }

        public Point(int x, int y)

        {

            this.x = x;

            this.y = y;

           

            objectCount++;

        }


        public double DistanceTo(Point mine)

        {

            int xDiff = this.x - mine.x;

            int yDiff = this.y - mine.y;

            

            return Math.Sqrt((xDiff * xDiff) + (yDiff * yDiff));

            

        }

    }

}


As you can see this is a class, I will now post the program code.

#region Using directives


using System;

using System.Collections.Generic;

using System.Text;


#endregion


namespace Classes

{

    class Program

    {

        static void DoWork()

        {

            Point origin = new Point();

            

            Point bottomRight = new Point(1024, 1280);

            double distance = origin.DistanceTo(bottomRight);

            

            Console.WriteLine("Distance is: {0}", distance);

            Console.WriteLine("No of Point objects: {0}", Point.ObjectCount());

        }


        static void Main(string[] args)

        {

            try

            {

                DoWork();

            }

            catch (Exception ex)

            {

                Console.WriteLine(ex.Message);

            }

        }

    }

}


So this is how the code works as far as I understand.
We create a new object with the x value -1 and y value -1.
Then we create a second object using the constructor with 2 parameters where we input the integers 1024 and 1280. However, since the constructor includes the code this.x = x;
this.y = y;
wouldnt that mean that the fields (which i made bold in the class code) that previously contained the values -1 and -1 are overwritten with the new values 1024 and 1280? Thus meaning that the method in the class which makes the calculation is using the same valus (1024 and 1280) twice?
Frankly, this is not the case and I simply cannot understand why. If anyone could explain to me where I make the miscalculation according to my mindset I would greatly appreciate that.

Thanks in advance.

#2
BuckAMayzing

BuckAMayzing

    Learning Programmer

  • Members
  • PipPipPip
  • 39 posts
Those values are treated as separate for each object. Your objectCount variable is declared as static, meaning that it is shared between different objects of that class. Here's what happens. You have the Point class (which by the way, there is a class included in the framework for a point) that you want to instantiate. The objectCount variable already exists as static, initialized as zero as you defined it in your code. So you instantiate a new Point, and you get an object that looks like this:

origin (variable name)
parameter x = -1
parameter y = -1

the static variable objectCount is incremented upon construction of the new object, so it now = 1.

Now, when you create the second point, it looks like this:

bottomRight (variable name)
parameter x = 1024
parameter y = 1280

the static variable is incremented again, making it 2.

The x and y variables for bottomRight are not the same x and y variables as for Origin. The "this" keyword references the current instance of the object, not the class itself. With your method header:

Point(int x, int y)

You create an overloaded constructor that will expect some two integers. You give it those integers when you specify the arguments 1024 and 1280. The original -1,-1 arguments have nothing to new with this new object. When you say:

this.x = x;
this.y = y;

You're stating that the "x" parameter for this object (declared in bold) is equal to the x value that is in the method header. For clarity:

public Point(int potato, int tomato)
{
     this.x = potato;
     this.y = tomato;
}

is accomplishing the same thing.

I hope I made that somewhat clear.

#3
noxrawr

noxrawr

    Newbie

  • Members
  • PipPip
  • 23 posts
Alright cheers for replying. You did indeed help me out some, but where I went wrong is that I thought that x and y cant have a different value than the other x and y since what I learnt is that when you change the value of a reference (class) the value changes for all objects. So when does the value change for all objects and when doesnt it?

Regards.

#4
BuckAMayzing

BuckAMayzing

    Learning Programmer

  • Members
  • PipPipPip
  • 39 posts
Firstly, static variables are shared among classes. Think of them as sort of a "global" variable for that class. If they are made public, they can actually be used for global variables.

Another situation one might commonly run into is the following:

point point1 = new Point(12,15);

MessageBox.Show(point1.ToString());

point point2 = point1;

point2.setX(25);
point2.setY(25);

MessageBox.Show(point1.ToString());

In the previous code block, the message boxes will show that x = 12 and y = 15 the first time, and x = 25 and y = 25 the second.

On the surface, it might look like this variable is being shared between the two objects, but in fact they are the same object. When you construct an object in C#, it becomes a 4(or 8 for 64 bit systems) byte value containing a memory address that is the starting address for that object in memory. When you say the following:

Point point2 = point1;

The code creates a new pointer that has the same value as point1, therefore pointing to the same object. To avoid this, you can use copy constructors (google has tons on that) or create a new one and then set the values afterward like so:

Point point1 = new Point(12,15);
Point point2 = new Point();

int x, y;
x = point1.getX();
y = point1.getY();

point2.setX(x);
point2.setY(y);

Of course, that is assuming that you have the methods coded to do that. As far as I can think of off the top of my head, those are the only two cases where the variable would be "shared" between to objects of the same class, aside from pointer issues if an object contains another object as a parameter.

#5
Hignar

Hignar

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 420 posts

noxrawr said:

Alright cheers for replying. You did indeed help me out some, but where I went wrong is that I thought that x and y cant have a different value than the other x and y since what I learnt is that when you change the value of a reference (class) the value changes for all objects. So when does the value change for all objects and when doesnt it?

Regards.

I think the main thing to understand is that each instance of the class will have it's own members x and y (object count is different because it is static and therefore 'shared' between the instances. Therefore the x and y belonging to origin and the x and y belonging to bottomRight and sepearate from one an other ie origin.x and bottomRight.x are not connected. I know the use of animals as classes is a bit cliché, but, if you consider a Dog class that has a weight member variable, then rover.weight and rex.weight won't be related as they are two different dogs.

The 'this' keyword refers to the current object. When used in the constructor as it is here it means it refers to the object that is calling the constructor. The reason that 'this' is used is to differentiate between the x member varaible and the x variable that is passed to the constructor. If you were to call the variables passed to the constructor by a different name you could write the constructor as
public Point(int a, int b) {
    x = a;
    y = c;
}
However, I find the need to find new variable names tiresome and (probably a better reason to use 'this') anyone looking at your code will understand the constructor by just looking at the signature.

Because the member variables for bottomRight are separate to those held be origin changing one point doesn't have an effect on the other and thus the fact that the member variables are passed by reference has no impact.
If there's a new way, I'll be the first in line.

But, it better work this time.

#6
noxrawr

noxrawr

    Newbie

  • Members
  • PipPip
  • 23 posts
very much appreciated, its all clear to me now :)