Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting object of a class to of another one

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.

like image 627
fhnaseer Avatar asked Sep 13 '13 10:09

fhnaseer


1 Answers

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

like image 81
letiagoalves Avatar answered Oct 07 '22 14:10

letiagoalves