Monday, April 11, 2011

Explicit and implicit conversion (C#)

A feature sadly rarely used, that can sometimes fasten coding are user-defined type conversion operators that are invoked with a cast. In the following example we define a struct Sentence that has an explicit conversion operator from string to Sentence.



In the Main method we are creating an instance of Sentence by casting a string to it.
The output of the program looks like this:



There is little difference in syntax for using an implicit conversion. It is done by declaring the conversion this way:



And using it without the cast:



Implicit conversion can improve code readability, however if you are using implicit conversion, you MUST MAKE SURE that the conversion will NEVER loose information or cause exceptions. The reason for this is the compiler, it will use the conversion and if that can cause a problem you will wreck havoc in your code.

No comments:

Post a Comment