User-Defined Conversions

Now that you have a sense of various supported built-in conversions, you can learn how you can define both implicit and explicit conversions on user-defined types. Although conversions can be handy, it’s recommended to keep a few design best practices in mind. The most important one involves implicit conversions, which should never lose any information, nor should they ever throw an exception as part of their operation. The reason for those recommendations is straightforward: Because an implicit conversion can be injected silently by the compiler, it might not be obvious at all what’s going on with the code.

Implicit conversions are considered by the compiler when an expected type (for example, for the target of an assignment ...

Get C# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.