J
jonpb
Hi, Is it possible to define a implicit operator from base to derived
types in C#?
I have a Point class and would like to derive a Vector class from it and
add a couple new vector related functions, like Normalize(). The problem
is Vector cannot use any of the Point operator overloads with a compile
time error that there is no implicit conversion from Point to Vector. I
tried adding an implicit operator to Vector:
public static implicit operator Vector3D(Point3D a)
{ return new Vector3D(pt); }
But that doesn't compile either resulting error CS0553. Here is some
relevant code snips:
public class Point3D
{
protected double _x, _y, _z;
public static Point3D operator *(Point3D a, double b)
{
return new Point3D(a.X * b, a.Y * b, a.Z * b);
}
}
public class Vector3D : Point3D
{
public Vector3D(Point3D pt) { _x = pt.X; _y = pt.Y; _z = pt.Z; }
public static implicit operator Vector3D(Point3D a)
{ return new Vector3D(pt); }
}
If it allows and explicit upcast conversion, I don't understand why it
would not allow me to define an implicit operator, being the author of
the classes I know that it is safe to upcast implicitly.
Thanks.
types in C#?
I have a Point class and would like to derive a Vector class from it and
add a couple new vector related functions, like Normalize(). The problem
is Vector cannot use any of the Point operator overloads with a compile
time error that there is no implicit conversion from Point to Vector. I
tried adding an implicit operator to Vector:
public static implicit operator Vector3D(Point3D a)
{ return new Vector3D(pt); }
But that doesn't compile either resulting error CS0553. Here is some
relevant code snips:
public class Point3D
{
protected double _x, _y, _z;
public static Point3D operator *(Point3D a, double b)
{
return new Point3D(a.X * b, a.Y * b, a.Z * b);
}
}
public class Vector3D : Point3D
{
public Vector3D(Point3D pt) { _x = pt.X; _y = pt.Y; _z = pt.Z; }
public static implicit operator Vector3D(Point3D a)
{ return new Vector3D(pt); }
}
If it allows and explicit upcast conversion, I don't understand why it
would not allow me to define an implicit operator, being the author of
the classes I know that it is safe to upcast implicitly.
Thanks.