Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialKari Soto
1,836 PointsField 'TreehouseDefense.Point.X' is never assigned to, and will always have its default value '0'
When I use the Console.WriteLine(isOnMap);, both results are true.
Game.cs:
using System;
namespace TreehouseDefense { class Game { public static void Main() { Map map = new Map(8, 5); Point point = new Point(4, 2);
bool isOnMap = map.OnMap(point);
Console.WriteLine(isOnMap);
point = new Point(10, 5);
isOnMap = map.OnMap(point);
Console.WriteLine(isOnMap);
}
}
}
Map.cs:
namespace TreehouseDefense { class Map { public readonly int Width; public readonly int Height;
public Map(int width, int height)
{
Width = width;
Height = height;
}
public bool OnMap(Point point)
{
return point.X >= 0 && point.X < Width &&
point.Y >=0 && point.Y < Height;
}
} }
Point.cs:
namespace TreehouseDefense { class Point { public readonly int X; public readonly int Y;
public Point(int x, int y) {
x = X;
y = Y;
}
} }
I wanted to solve it myself but even after watching the last few videos multiple times, I still have no idea what is the purpose of constructs or how they work.
2 Answers
Steven Parker
231,198 PointsYour constructor for the Point class has the initializations reversed.
In your constructor:
public Point(int x, int y) {
x = X;
y = Y;
}
The idea is to use the passed-in arguments (lower case) to assign your internal class variables (UPPER case). But as it is, the assignments are reversed so that every point object location will always be 0,0 (which is on the map). This is what the warning message was trying to tell you, at least about "X" (but "Y" has the same issue).
Turn the assignments around so the internal variables get initialized correctly:
public Point(int x, int y) {
X = x; // put the value from the argument into the readonly variable.
Y = y;
}
Mark Duplock
9,549 PointsGlad I'm not the only one who made this mistake! :)
Kari Soto
1,836 PointsKari Soto
1,836 PointsThank you. Hopefully by the time I finish C# courses, I can be able to find and solve these problems myself.