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.


Sign In
Create Account


Back to top









