Converting object of a class to of another one
Sounds like you could use generics here:
public class GenericClass<T>
{
T X { get; set; }
T Y { get; set; }
T Z { get; set; }
}
GenericClass<float> floatClass = new GenericClass<float>();
GenericClass<double> doubleClass = new GenericClass<double>();
Use a conversion operator:
public static explicit operator FloatClass (DoubleClass c) {
FloatCass fc = new FloatClass();
fc.X = (float) c.X;
fc.Y = (float) c.Y;
fc.Z = (float) c.Z;
return fc;
}
And then just use it:
var convertedObject = (FloatClass) doubleObject;
Edit
I changed the operator to explicit
instead of implicit
since I was using a FloatClass
cast in the example. I prefer to use explicit
over implicit
so it forces me to confirm what type the object will be converted to (to me it means less distraction errors + readability).
However, you can use implicit
conversion and then you would just need to do:
var convertedObject = doubleObject;
Reference