User-defined implicit conversions |
A: User-defined implicit conversions allow your class to define conversions
from other classes (or basic types), without requiring a cast, or requiring
you to call a conversion function.
For example, if you have a class called Complex and you have defined an
implicit conversion from float then you can use it like this:
Without user-defined implicit conversions, you would have to use one of the
following less-convenient statements:
| Complex c2 = (Complex)12.345F; Complex c3 = Complex.ValueOf(12.345F);
|
A: Yes. VB4 did not have the ability for users to define their own implicit
conversions. Instead, it came with a large set of built-in, "convenient"
conversions. This supposed "convenience" caused so many problems that VB programmers
nicknamed this feature "Evil Type Coercion".
You can read more about it here:
http://www.devx.com/premier/mgznarch/vbpj/1995/11nov95/progtech.pdf
A: Yes, many programming languages including C do some implicit type conversions,
such as from int to long. But such built-in implicit conversions are usually
limited, well understood and very strict.
A: Implicit type conversions decrease type error detection ability of the compiler.
Fewer of your programming errors will be caught by the compiler, which leads to
less reliable software.
For example, if you erroneously assigned an integer to a variable of type Foo, the
compiler will catch the error. However if you have defined an implicit conversion
from integer to Foo, then the compiler will assume you meant to convert the integer
to type Foo and then store the value, so your error will not be caught. If this is
really what you meant, then it is better to make it explicit by calling a conversion
function like this:
| Foo f = Foo.ValueOf(123);
|
A: The issues with implicit type conversion have nothing to do with whether there
is loss of precision or not. See above.
A: The evils of implicit type conversion outweigh the benefits.
C# Best Practice
Do not use user-defined implicit conversions
|
[Back to Index]
|