C# FAQ

User-defined implicit conversions

Q: What do user-defined implicit conversions buy you?
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:
   Complex c1 = 12.345F;
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);

Q: Isn't this what wreaked havoc in VB4?
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

Q: Don't many programming languages have built-in implicit conversions?
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.

Q: How does implicit type conversion reduce software reliability?
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);

Q: Are implicit type conversions OK when there is no loss of precision?
A: The issues with implicit type conversion have nothing to do with whether there is loss of precision or not. See above.

Q: What can we conclude from all this?
A: The evils of implicit type conversion outweigh the benefits.

C# Best Practice

Do not use user-defined implicit conversions

[Back to Index]













1