I have created a custom Point class in C#, because the regular Point class doesn't have a lot of the functions I need for it. The problem that I face, is that when I create a new custom Point class, and then create another variable to represent that newly created class, they are assigned the same addresses in memory. I remember to change this in C++ you had to use & and *, but in C# I don't know how to do this.
Here's an example of the problem I'm facing
public string Example()
{
CustomPoint pt = new CustomPoint(0, 0);
CustomPoint ptbuf = pt;
ptbuf.X = 100;
return(pt.X.ToString()); // returns the value of 100, instead of 0, which it should be
}
And this is what should happen, and what does happen with a normal Point class
public string Example2()
{
Point pt = new Point(0, 0);
Point ptbuf = pt;
ptbuf.X = 100;
return (pt.X.ToString()); // returns the value 0
}
Also, here is the part of the CustomPoint class I've made that isn't working right.
public class CustomPoint
{
public float X { get; set; }
public float Y { get; set; }
}
Thanks for your help.
You should make it a struct, not a class. Structs are value types and classes are reference types, which means that when you assign pt to ptbuf, you pass only the reference of the object, not a copy. See https://msdn.microsoft.com/en-us/library/ms173109.aspx for more information on the subject
As Henk states, you should use a struct
and make it immutable.
Instead of creating your own CustomPoint
class what not just extend the Point
class.
public static class PointExtentsions
{
public static int MyMethod(this Point point) { ... }
}
The above will add MyMethod
to any Point
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.