Convert One Type to Another
Implement a conversion operator. There are two types of conversion operators:
implicit and explicit. To understand the difference, we’ll implement a
new struct called Vertex3i that is the same as Vertex3d, except the dimensions
are integers instead of doubles.
Explicit Conversion (Loss of Precision)
Explicit conversion is encouraged when the conversion will result in a loss of precision.
When you’re converting from System.Double to System.Int32, for example,
all of the decimal precision is lost. You don’t (necessarily) want the compiler to allow
this conversion automatically, so you make it explicit. This code goes in the Vertex3d
Vertex3d vd = new Vertex3d(1.5, 2.5, 3.5);
Vertex3i vi = (Vertex3i)vd;
If you tried it without the cast, you would get the following:
//Vertex3i vi = vd;
Error: Cannot implicitly convert type ‘Vertex3d’ to ‘Vertex3i’.
An explicit conversion exists (are you missing a cast?)
Implicit Conversion (No Loss of Precision)
If there will not be any loss in precision, then the conversion can be implicit, meaning
the compiler will allow you to assign the type with no explicit conversion. We can
implement this type of conversion in the Vertex3i class because it can convert up to a
double with no loss of precision.
Vertex3i vi = new Vertex3i(1, 2, 3);
Vertex3d vd = vi;
Re: Convert One Type to Another
You sometimes need to copy a value of variable of one type into a variable of another type.It is called type conversions.
For example, you might have an integer variable that you necessary to pass to a method whose parameter is like as double.
These can be done by following ways:
Implicit conversions: This type of conversion is type safe and no data
will be lost.conversions is done from smaller to larger integral types.
int no = 123;
long logg = no;
Explicit conversions : Explicit conversions require a cast operator.In this conversion both source and destination
variables must be compatible, but there is a risk of data loss because the type of the destination variable is a smaller
size than the type of source variable.
For Example: double a = 3724.7;
// Casting double to int.
desti= (target type)source;
s = (int)a;
User-defined conversions: User-defined conversions are implement by certain methods that you can define to enable both
explicit and implicit conversions between custom types that do not have a base class derived class relationship.
|All times are GMT +5.5. The time now is 01:49.|