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

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

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

72 ❘ CHAPTER 4 Data Types, Variables, and Constants<br />

For example, the following code defines a string that contains four column headers’ values separated<br />

by tabs.<br />

string header = "Item\tPrice Each\tQuantity\tTotal";<br />

If a string contains backslashes but no escape sequences, it can be cumbersome to represent<br />

each backslash with \\. For example, Windows file paths such as C:\Temp\Projects\CurrentWork\<br />

project.txt may include a lot of backslashes. The following code shows how you would assign this<br />

value to a string variable.<br />

string filename = "C:\\Temp\\Projects\\CurrentWork\\project.txt";<br />

In <strong>C#</strong> you can place an @ symbol in front of a string to make working with this kind of text easier.<br />

In that case the string ignores all escape sequences and includes the characters between its quotes as<br />

they appear.<br />

string filename = @"C:\Temp\Projects\CurrentWork\project.txt";<br />

This kind of string continues until it reaches its closing " and can even span multiple lines.<br />

If you need the string to contain a " character, you can’t simply type it in the text because the program<br />

would think it represented the end of the string. You also cannot use \" because this kind of<br />

string ignores escape sequences.<br />

Instead of adding a " character to the string, double up the character. The following code initializes<br />

a string variable to hold a two-line string that contains double quotes and then displays it in the<br />

Console window.<br />

string greeting = @"Welcome to Project<br />

""Do What I Meant""";<br />

Console.WriteLine(greeting);<br />

The following text shows the result.<br />

Welcome to Project<br />

"Do What I Meant"<br />

Data Type Conversion<br />

Normally, you assign a value to a variable that has the same data type as the value. For example,<br />

you assign a string value to a string variable, you assign an integer value to an int variable, and so<br />

forth. Often, however, a program must convert a value from one data type to another. For example,<br />

it might need to convert an int into a float or it might need to convert a string containing a<br />

numeric value into a decimal.<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!