-1

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.

Max Brodin
  • 3,903
  • 1
  • 14
  • 23
foo bar
  • 75
  • 6
  • `Point` is not a `class` but a `struct`. [What is the difference between a reference type and value type in c#?](http://stackoverflow.com/questions/5057267/what-is-the-difference-between-a-reference-type-and-value-type-in-c) – Selman Genç Jan 28 '15 at 21:53
  • It is because you define your datatype as a reference type, if it is a value type, you get the value 100. – Matt Jan 28 '15 at 21:57

2 Answers2

4

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

slvnperron
  • 1,323
  • 10
  • 13
0

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.

Richard Schneider
  • 34,944
  • 9
  • 57
  • 73
  • You can't inherit (extend) a struct, and the POINT in the library is the old Win32 mutable type. Not a good starting point. – H H Jan 29 '15 at 09:31
  • @HenkHolterman, you can not inherit from a `struct` put you can extend them as my example shows. – Richard Schneider Jan 29 '15 at 19:13