I have two classes which have are nearly equal except the data types stored in them. One class contains all double values while other contains all float values.
class DoubleClass
{
double X;
double Y;
double Z;
}
class FloatClass
{
float X;
float Y;
float Z;
}
Now I have a point of DoubleClass which I want to convert to FloatClass.
var doubleObject = new DoubleClass();
var convertedObject = (FloatClass)doubleObject; // TODO: This
One simple way is to make a method which creates a new FloatClass object, fills all values and return it. Is there any other efficient way to do this.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With