15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

160 ❘ ChaPTer 7 OperAtOrs And cAsts<br />

In this case, you will not get an error, but you also will not get the result you expect. If you run this code<br />

<strong>and</strong> output the value stored in i, this is what you get:<br />

-1294967296<br />

It is good practice to assume that an explicit cast will not give the results you expect. As you saw earlier, <strong>C#</strong><br />

provides a checked operator that you can use to test whether an operation causes an arithmetic overflow.<br />

You can use the checked operator to check that a cast is safe <strong>and</strong> to force the runtime to throw an overflow<br />

exception if it is not:<br />

long val = 3000000000;<br />

int i = checked((int)val);<br />

Bearing in mind that all explicit casts are potentially unsafe, you should take care to include code in your<br />

application to deal with possible failures of the casts. Chapter 15, “Errors <strong>and</strong> Exceptions,” introduces<br />

structured exception h<strong>and</strong>ling using the try <strong>and</strong> catch statements.<br />

Using casts, you can convert most primitive data types from one type to another; for example, in this code,<br />

the value 0.5 is added to price, <strong>and</strong> the total is cast to an int:<br />

double price = 25.30;<br />

int approximatePrice = (int)(price + 0.5);<br />

This gives the price rounded to the nearest dollar. However, in this conversion, data is lost — namely,<br />

everything after the decimal point. Therefore, such a conversion should never be used if you want to go<br />

on to do more calculations using this modified price value. However, it is useful if you want to output the<br />

approximate value of a completed or partially completed calculation — if you do not want to bother the<br />

user with lots of figures after the decimal point.<br />

This example shows what happens if you convert an unsigned integer into a char:<br />

ushort c = 43;<br />

char symbol = (char)c;<br />

Console.WriteLine(symbol);<br />

The output is the character that has an ASCII number of 43, the + sign. You can try any kind of conversion<br />

you want between the numeric types (including char), <strong>and</strong> it will work, such as converting a decimal into a<br />

char, or vice versa.<br />

Converting between value types is not restricted to isolated variables, as you have seen. You can convert an<br />

array element of type double to a struct member variable of type int:<br />

struct ItemDetails<br />

{<br />

public string Description;<br />

public int ApproxPrice;<br />

}<br />

//..<br />

double[] Prices = { 25.30, 26.20, 27.40, 30.00 };<br />

ItemDetails id;<br />

id.Description = “Hello there.”;<br />

id.ApproxPrice = (int)(Prices[0] + 0.5);<br />

To convert a nullable type to a non-nullable type or another nullable type where data loss may occur,<br />

you must use an explicit cast. This is true even when converting between elements with the same basic<br />

underlying type, for example, int to int or float to float. This is because the nullable type may<br />

have the value null, which cannot be represented by the non-nullable type. As long as an explicit cast<br />

between two equivalent non-nullable types is possible, so is the explicit cast between nullable types.<br />

However, when casting from a nullable to non-nullable type <strong>and</strong> the variable has the value null, an<br />

InvalidOperationException is thrown. For example:<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!