15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

182 ❘ ChaPTer 7 OperAtOrs And cAsts<br />

In fact, Console.WriteLine() has another overload that takes a double as a parameter <strong>and</strong> displays the<br />

value of that double. If you look closely at the output from the first SimpleCurrency example, you will<br />

find the very first line of output displayed Currency as a double, using this overload. In that example,<br />

there wasn’t a direct cast from Currency to uint, so the compiler picked Currency-to-float-to-double<br />

as its preferred way of matching up the available casts to the available Console.WriteLine() overloads.<br />

However, now that there is a direct cast to uint available in SimpleCurrency2, the compiler has opted<br />

for this route.<br />

The upshot of this is that if you have a method call that takes several overloads, <strong>and</strong> you attempt to pass it a<br />

parameter whose data type doesn’t match any of the overloads exactly, then you are forcing the compiler to<br />

decide not only what casts to use to perform the data conversion, but which overload, <strong>and</strong> hence which data<br />

conversion, to pick. The compiler always works logically <strong>and</strong> according to strict rules, but the results may<br />

not be what you expected. If there is any doubt, you are better off specifying which cast to use explicitly.<br />

summary<br />

This chapter looked at the st<strong>and</strong>ard operators provided by <strong>C#</strong>, described the mechanics of object equality,<br />

<strong>and</strong> examined how the compiler converts the st<strong>and</strong>ard data types from one to another. It also demonstrated<br />

how you can implement custom operator support on your data types using operator overloads. Finally, this<br />

chapter looked at a special type of operator overload, the cast operator, which allows you to specify how<br />

instances of your types are converted to other data types.<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!