Class aliases

  • Thread starter Thread starter hstagni
  • Start date Start date
H

hstagni

Supose I have class named Point3D, which stores x, y, z coordinates
and Sometimes Point3D is used like a Point2D:
-Point3D has a constructor that takes three arguments and another one
that takes only two args setting x and y and z = 1.
-There is some method Foo() that takes a Point3D as a parameter but
only use its x and y coordinates

- >Instead of calling "Foo(new Point3D(3, 14))", I want other classes
to call "Foo(new Point2D(3, 14))", with Point2D being actually an
alias for Point3D. Maybe the best solution is to create a Point3D
subclass called Point2D, but I was looking for a quick and dirty
solution.

I know I can use "using Point2D = Point3D", but it's only valid in the
current file. Is there a "using Point2D = Point3D" that works on the
entire namespace?
 
hstagni said:
I know I can use "using Point2D = Point3D", but it's only valid in the
current file. Is there a "using Point2D = Point3D" that works on the
entire namespace?

You could operator overloading:

void Foo(Point2D value)
{
Foo(new Point3D(value.X, value.Y));
}

Or, you could provide an conversion operator (either implicit or
explicit) to handle the conversion from Point3D to Point2D:

class Point3D
{
// ...
public static implicit operator Point3D(Point2D value)
{
return new Point3D(value.X, value.Y);
}
}
 
hstagni said:
Supose I have class named Point3D, which stores x, y, z coordinates
and Sometimes Point3D is used like a Point2D:
-Point3D has a constructor that takes three arguments and another one
that takes only two args setting x and y and z = 1.
-There is some method Foo() that takes a Point3D as a parameter but
only use its x and y coordinates

- >Instead of calling "Foo(new Point3D(3, 14))", I want other classes
to call "Foo(new Point2D(3, 14))", with Point2D being actually an
alias for Point3D. Maybe the best solution is to create a Point3D
subclass called Point2D, but I was looking for a quick and dirty
solution.

I know I can use "using Point2D = Point3D", but it's only valid in the
current file. Is there a "using Point2D = Point3D" that works on the
entire namespace?

Normally, Point3D would subclass Point2D, as it adds the z property.

Another approach you could consider is an IPoint2D interface, which just
exposes the x and y properties.
 
Back
Top