When should you use the "implicit" or "explicit" keyword when overloading conversion operators?

I am currently learning C #. The manual does not indicate when to use the keyword implicit

or explicit

when overloading conversion operators.

The example it provides looks like this:

When Class1

contains a type field int

and Class2

contains a type field double

, we must define an explicit conversion from Class2

to Class1

, and an implicit conversion from Class1

to Class2

.

The tutorial doesn't say what happens if I use the wrong keyword.

But if it Class1

contains a complex subclass and Class2

contains another subclass, which keyword should be used between implicit

and explicit

? Can anyone provide a clear explanation? Many thanks.

+3


source to share


1 answer


Implicit conversions: No special syntax is required because the conversion is type-safe and data will not be lost. Examples include conversions from smaller to larger integral types, and conversions from derived classes to base classes .

Explicit conversions (castings):

Explicit conversions require a translation operator. Casting is required when information might be lost during a conversion or when a conversion might fail for other reasons. Typical examples include numeric conversions to a type with less precision or range, and converting an instance of a base class to a derived class.

Mark the bold texts in this explanation. Here is a detailed article on MSDN



Here's some sample code:

// Create a new derived type.
Giraffe g = new Giraffe();

// Implicit conversion to base type is safe.
Animal a = g;

// Explicit conversion is required to cast back
// to derived type. Note: This will compile but will
// throw an exception at run time if the right-side
// object is not in fact a Giraffe.
Giraffe g2 = (Giraffe) a;

      

+1


source







All Articles