03.01.2015 Views

C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

Casting and Converting Values ❘ 735<br />

The integer functions ToInt16, ToInt32, ToInt64, ToUInt16, ToUInt32, and ToUInt64 also provide<br />

overloaded versions that take as parameters a string value and a base, which can be 2, 8, 10, or 16 to<br />

indicate whether the string is in binary, octal, decimal, or hexadecimal, respectively. For example, the<br />

following statement converts the binary value 00100100 into the integer value 36.<br />

int value = Convert.ToInt32("00100100", 2)<br />

The BitConverter class provides methods for converting variables to and from arrays of bytes.<br />

Widening and Narrowing Conversions<br />

In a widening conversion, the destination data type can hold any value held by the source data type. For<br />

example, a long can hold any value that fits in an int, so the following code is a widening conversion.<br />

int intValue = 100;<br />

long longValue = intValue;<br />

Because this conversion must succeed, no casting or other operation is required.<br />

In a narrowing conversion, the destination data type may not hold any value held by the source<br />

data type. For example, an int cannot necessarily hold any value that fits in a long, so the following<br />

code is a narrowing conversion.<br />

long longValue = 100;<br />

int intValue = (long)longValue;<br />

Because this is a narrowing conversion, the casting operator is required, and the operation may<br />

throw an exception if the value cannot fit in the destination data type.<br />

Converting Objects<br />

Converting an object into a less derived ancestor class is a widening conversion, so it doesn’t require<br />

casting. Conversely converting an object into a more derived descendant class is a narrowing conversion,<br />

so it requires casting.<br />

For example, suppose the Employee class is derived from the Person class. Then the following code<br />

shows a widening conversion followed by a narrowing conversion.<br />

Employee employee = new Employee();<br />

Person person = new Person();<br />

Employee employee2 = (Employee)person;<br />

The as Operator<br />

The as operator provides a shorthand for converting objects from one type to another. The following<br />

code converts the value in variable person into a Student and saves it in variable student.<br />

student = person as Student;<br />

If the value cannot be converted into a Student (for example, if person is a Janitor), then the as<br />

operator returns null.<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!