Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - reference wrapper for value type

Tags:

c#

.net

I want to use c# Point type as a reference type (it is a struct). I thought of having a class CPoint, which would contain a Point member. Is there any way to raise the members of the Point to act as members of the Cpoint. I am trying to avoid

cpoint.point.X;
cpoint.point.Y;

I would like to do

cpoint.X;
cpoint.Y;

as well as keep all the conversions, operators, Empty, etc.
Can this easily be done?

like image 869
Baruch Avatar asked Jan 04 '12 22:01

Baruch


3 Answers

Something like this?

public class CPoint {
  private Point _point = new Point(0,0);
  public double X { get { return _point.X; } set { _point.X = value; } }
  public double Y { get { return _point.Y; } set { _point.Y = value; } }
  public CPoint() { }
  public CPoint(Point p) { _point = p; }
  public static implicit operator CPoint(Point p) { return new CPoint(p); }
  public static implicit operator Point(CPoint cp) { return cp._point; } 
}

EDIT: If you want to have this automatically converted to/from points, implement implicit conversions as per above. Note I haven't tested these, but they should work. More info here: http://msdn.microsoft.com/en-us/library/z5z9kes2.aspx

like image 170
Chris Shain Avatar answered Sep 29 '22 11:09

Chris Shain


I think the only way is to re-write and pass-through all properties, operators and methods, just like this:

public class PointReference {
  private Point point;

  public int X { get { return point.X; } set { point.X = value; } }
}

(The change of class name is intended; CPoint isn't very expressive.)

like image 43
Yogu Avatar answered Sep 29 '22 12:09

Yogu


If you need it to act like a reference type then use the ref keyword. It will allow you to pass by reference. With this you will get all of the performance benefits from it being a struct, as well as knowing specifically when you expect it to act like a reference. You can also use the out keyword to return a parameter by reference.

If you need it to be able to represent null then use a Nullable<T>

If you simply want to access is like foo.MyPoint.X then declare it as a field like so:

class Foo {
  public Point MyPoint;
}
like image 35
Charles Lambert Avatar answered Sep 29 '22 11:09

Charles Lambert