struct in C# doesn't work as expected - c#

I'm working on a simple application and I'm a little confused. I have a simple struct Point with int x and int y. And I use it for Line
public class Line : Shape {
public Line() {
PointA = new Point(x: 0, y: 0);
PointB = new Point(x: 0, y: 0);
}
public Point PointA { get; set; }
public Point PointB { get; set; }
}
and somewhere
var line = new Line();
line.PointB = new Point(x: 4, y: 2);
Console.WriteLine($"Line start at {line.PointA.GetX()}:{line.PointA.GetY()}; end at {line.PointB.GetX()}:{line.PointB.GetY()}");
for (int i = 0; i < 10; i++) {
line.PointB.IncrementX();
line.PointB.IncrementY();
}
Console.WriteLine($"Line start at {line.PointA.GetX()}:{line.PointA.GetY()}; end at {line.PointB.GetX()}:{line.PointB.GetY()}");
Here need to increment x and y of Point but result doesn't change:
Line start at 0:0; end at 4:2
Line start at 0:0; end at 4:2
What I'm doing wrong? It seems strange. Are there some specific rules to use struct in C#. I know that this is a value type but I think it is a good for Point. All examples uses struct for Point. Please help?
Point:
public struct Point {
private int _x;
private int _y;
public Point(int x, int y)
: this() {
_x = x;
_y = y;
}
public void IncrementX() {
_x++;
}
public void IncrementY() {
_y++;
}
public int GetX() {
return _x;
}
public int GetY() {
return _y;
}
}

Struct is a value type. And it is passed by value (i.e. by creating copy of all fields) instead of passing reference to struct instance. So when you do
line.PointB.IncrementX()
When you call getter of PropertyB, it returns copy of Point which is stored at PropertyB backing field. And then you call increment on copy. Thus original value will stay unchanged.
Further reading: Value and Reference Types and especially Mutating Readonly Structs which says
mutable value types are evil. Try to always make value types
immutable.
What you can do if you want to actually move line point?
Change Point type to class. Then it will be passed by reference, and all methods will be called on original point which you store in Line.
Assign new (modified) point instance to line
I.e. you should store copy, change it and assign back
var point = line.PointB; // get copy
point.IncrementX(); // mutate copy
point.IncrementY();
line.PointB = point; // assign copy of copy
You can also make your Point struct immutable (the best thing you can do for value types):
public struct Point
{
public Point(int x, int y)
{
X = x;
Y = y;
}
public int X { get; }
public int Y { get; }
public Point IncrementX() => new Point(X + 1, Y);
public Point IncrementY() => new Point(X, Y + 1);
public Point Move(int dx, int dy) => new Point(X + dx, Y + dy);
}
And now changing location will look like
line.PointB = line.PointB.Move(1, 1);

Related

How to fix Console Writing the name of the Class? [duplicate]

This question already has answers here:
Class List Keeps Printing Out As Class Name In Console?
(4 answers)
Closed 3 years ago.
I am new to C# and I am struggling with this since hours and would appreciate your help.
I want to create a Polygon and Write down each position of the points.
Currently I have this:
-Class Point
class Point
{
private int x;
private int y;
public Point(int x2, int y2)
{
x = x2;
y = y2;
}
}
-Class Polygon
class Polygon
{
private Point[] Points;
public Polygon(params Point[] a)
{
Points = new Point[a.Length];
for (int i = 0; i < a.Length; i++)
{
Points[i] = a[i];
}
}
public Point this[int index]
{
get { return Points[index]; }
set { Points[index] = value;}
}
}
Now I have this in my main:
Polygon First= new Polygon(new Point(7,4), new Point(4,1), new Point(2, 1));
First[0] = new Point(3, 4);
Console.WriteLine("points of polygon ");
for (int i = 0; i < First.PointCounter; i++)
{
Console.WriteLine(First[i]);
}
But now instead of seeing each position of the Point after "points of polygon" I see this in my Console: https://imgur.com/Z5aVFMK
How it should look like: https://imgur.com/a/aFkdrEF
How it should look like: https://imgur.com/a/aFkdrEF
I added an override of ToString so that your Point class has the expected output when converted to string. An output like "x:3 y:4".
class Point
{
public int x { get; private set; }
public int y { get; private set; }
public Point(int x2, int y2)
{
x = x2;
y = y2;
}
public override string ToString()
{
return $"x:{x,-3} y:{y,-3}";
}
}
As it is now, it is a good candidate for becoming a struct instead of class.
C# is not "interpreted" like other languages, so the Console.WriteLine method won't guess what you're trying to have printed.
To give the result you're looking for, with your current code, you would have to provide public properties to your Point class:
public int X { get { return x;} set{ x = value;} }
public int Y { get { return y;} set{ y = value;} }
After which you could now access those properties in your for loop:
for (int i = 0; i < First.PointCounter; i++)
{
Console.WriteLine($"x:{First[i].X} y:{First[i].Y}");
}

2D-array as a class property - how to create them the C# way?

I am trying to create a class with a property that is a two-dimensional array. The array will hold various x,y coordinates on a grid (e.g. 0,1 or 3,7) and the size of the array is dependent on a class property called size.
How would you go about creating this array in C#? I have given my solution below, but having very little C# experience and coming from a Python background with some javascript knowledge, it feels like that there is a better solution to this problem.
Could one of you C# wizards enlighten me, please?
Thanks in advance for your help.
Here is my code:
public class Obj
{
int Size; // Defines length of array
int[,] Pos;
// constructor
public Obj(int size)
{
this.Size = size;
this.Pos = new int[size, 2];
}
public void set_coord(int index, int x, int y)
{
if (index >= this.Size) {
Console.WriteLine("Catch OutOfRangeException");
}
else
{
this.Pos[index, 0] = x;
this.Pos[index, 1] = y;
}
}
You could create a List instead of a class, and have an internal sub class to represent your points.
Like this
public class Obj{
int Size;
List<Point> Pos = new List<Point>();
public Obj(int size){
this.Size = size;
}
public set_coord(int index, int x, int y){
if(index >= this.Size){
Console.Writeline("Catch OutOfRangeException")
}else{
this.Pos.Add(new Point(x,y));
}
}
}
class Point{
int x = 0;
int y = 0;
public Point(int xCor, int yCor){
this.x = xCor;
this.y = yCor;
}
}
A struct is the ideal approach for this. A full blown class may not be necessary, but it depends.
https://msdn.microsoft.com/en-us/library/ah19swz4.aspx
public struct Coordinates
{
public int coordX;
public int coordY;
}
The property then in your class could be set like this:
var Obj = new Obj();
List<Coordinates> listOfCoords = new List<Coordinates>();
var coord = new Coordinates();
coord.X = 20;
coord.Y = 15
listOfCoords.Add(coord);
Obj.Pos = listOfCoords
Keep in mind that Structs cannot be inherited from, or inherit, other classes or structs, as well as a few other gotchas. If you need these features, or the data in your struct is prone to modification after it is created (in other words, the data is NOT immutable), consider a small class instead.
https://msdn.microsoft.com/en-us/library/0taef578.aspx

How to tie one variable to another

I have this bit of code:
Brick brick1= new Brick(parent.X - 1,parent.Y);
X & Y are integers,
Basiclly what i want to do is: when the x of the parent brick changes, the x of brick1 changes,where it dosnt matter the value of parent.X, brick1.X will always be equal to parent.X - 1
Is there an way of accomplishing this?
Assuming that Brick is not a struct you could do this. You could also do this through inheritance with a ChildBrick class but unless you need the added complication, at least in my mind, it is simpler to just allow Brick to have a parent that is a Brick and add a constructor for the parent. Then if you retrieve a value and it needs to be computed from the parent you just check for whether you have a parent and calculate accordingly.
class Brick
{
private Brick _parent;
private int _x;
private int _y;
Brick(Brick parent) {_parent = parent);}
Brick(int x, int y)
{
_x = x;
_y=y;
}
public int X
{
get
{
if (_parent != null) return _parent.X - 1;
return _x;
}
}
public int Y
{
get
{
if (_parent != null) return _parent.Y;
return _y;
}
}
}
Just make brick1 a derived class with a calculated read only property
public class childBrick: Brick
{
public new float X
{
get { return base.X - 1.0 }
private set { base.X = value; }
}
public static Brick Make( float x, float y)
{
return new childBrick
{
X = x;
Y = y;
}
}
}
use it like this
Brick brick1 = childBrick.Make(parent.X - 1,parent.Y);

I do not understand why I get CS0120

I am having one error and have searched for answers in my book and watched tutorials for this particular subject. The large gap is to indicate another class I added called Point
class Program
{
private static Point another;
static void Main(string[] args)
{
Point origin = new Point(1366, 768);
Point bottomRight = another;
double distance = origin.DistanceTo(bottomRight);
Console.WriteLine("Distance is: {0}", distance);
Console.WriteLine("Number of Point objects: {0}", Point.ObjectCount());
}
}
class Point {
private int x, y;
private int objectCount = 0;
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 other)
{
int xDiff = this.x - other.x;
int yDiff = this.y - other.y;
double distance = Math.Sqrt((xDiff * xDiff) + (yDiff * yDiff));
return distance;
}
public static int ObjectCount()
{
**return objectCount;**
}
}
Your ObjectCount() method is static method while your property is not.
public static int ObjectCount()
As you are reading from a property which is not allocated in your code. So, remove the static keyword from the methods signature.
public int ObjectCount()
{
return objectCount;
}
1) please post full code in separate blocks, also please tell people where exactly you get the error;
2) my guess is that error CS0120 comes from the line: Console.WriteLine("Number of Point objects: {0}", Point.ObjectCount());
Yet again, I guess that you wanted to count all of the Point objects created. Your mistake is making objectCount an instance member.
You see, every instance of Point class will have its own objectCount, and it will always be 1 after constructor finishes. For the very same reason you can not call Point.ObjectCount() and return objectCount from it, because objectCount is not a static member, it's bound to an instance.
To fix your code, make objectCount static. That way there would be only one objectCount for all instances of Point.

C# XNA pass by reference classes in constructor

I'm making a vector graphics game in XNA. I've designed a Line class to rotate around a central point to help draw specific shapes. In order to maintain a single point of truth, is there a way to pass a reference to the center of the shape to all of the lines I create, so that updating the center's position will also update the lines' positions? I thought something like this would work:
class Line
{
private Vector2 start;
private double length;
private double angle;
public Line(ref Vector2 start, double length, double angle){
this.start = start;
this.length = length;
this.angle = angle;
}
}
class Obj
{
private Vector2 center;
private Line[] lines;
public Obj(){
center = new Vector2(50,50);
lines = new Lines[5];
for (int i = 0; i < 5; i++){
lines[i] = new Line(ref center,30, (i/5 * 2 * Math.PI));
}
}
}
but the lines do not update when I move the center. What am I doing wrong?
Although the struct is correctly passed by reference to Line, when you assign it internally:
public Line(ref Vector2 start, double length, double angle){
this.start = start;
}
You are actually taking a copy of the struct.
If you ever find yourself needing reference type semantics of struct beyond passing it to a single method then you likely need to reconsider using class.
You can either re-implement the type in a class or wrap the Vector2 in a class and use that:
class Vector2Class
{
public Vector2 Centre;
public Vector2Class(Vector2 inner)
{
Centre = inner;
}
}
class Line
{
private Vector2Class _centre;
public Line(Vector2Class centre)
{
_centre = centre;
}
}
Be aware that you are still working against a copy, but if you share the class you'll all be working on the same copy.
Personally, I would avoid the wrapper and make my own class for representing "centre". This is supported by the largely accepted idea that struct types should be immutable, but you seem to need to mutate the values to keep the representation true.
class CentreVector<T>
{
public <T> X { get; set; }
public <T> Y { get; set; }
}
This only lets you share the data, it doesn't actually notify the lines that the centre has changed. For that you would need some sort of event.
Edited with alternative solution
The problem you're having is because Vector2 is a value type, you're correctly passing it by ref in your methods parameter but then making a local copy of it with the assignment.
I'm not totally sure if you could maintain a pointer to Vector2 in the way that you're thinking but you could create your own Vector2 class that would be a reference type.
class ObjectVector2
{
public float X { get;set; }
public float Y { get; set; }
}
I would like to suggest a slightly different way to achieve the same result by holding a reference to the obj that the lines are a part of.
class Line
{
private Vector2 Center { get { return parent.center; } }
private double length;
private double angle;
Obj parent;
public Line(Obj parent, double length, double angle)
{
this.parent = parent;
this.length = length;
this.angle = angle;
}
}
class Obj
{
public Vector2 center;
private Line[] lines;
public Obj()
{
center = new Vector2(50, 50);
lines = new Lines[5];
for (int i = 0; i < 5; i++)
{
// passing the reference to this Obj in the line constructor.
lines[i] = new Line(this, 30, (i / 5 * 2 * Math.PI));
}
}
}

Categories