Using Literal Strings


Table 4.1 showed a list of special characters. These characters are characters that must be represented using the escape character (\) . In C# it is also possible to create literal strings. Literal strings enable you to use special characters like the backslash or double quotes without having to use special codes or the escape character.

To create a literal string:

  1. Type string str where str is the name of the variable to hold the string.

  2. Type = @"the string" ; (the @ character followed by double quotes, followed by any string context, followed by another double quote) ( Figure 4.36 ).

    Figure 4.36 Literal strings enable you to represent special characters without using escape sequences.
     string lit =  @  "this is a boring literal string"; 

graphics/tick.gif Tips

  • You can use backslashes in literal strings without having to use two backslashes ( Figure 4.37 ).

    Figure 4.37 Because the backslash is used to represent escape sequences, to add a backslash you need to type two backslashes. However, with literal strings you don't use escape sequences, so you can use the backslash as a backslash.
     //non-literal string requires double backslash string windir1 = "c:\windows\system32\"; //literal string can use a single backslash string windir2 =  @"c:\windows\system32\"  ; 
  • To specify the double-quote character you can put two double-quote characters together ( Figure 4.38 ).

    Figure 4.38 The double-quote character is a problem no matter what type of string you use, because it tells the compiler where the string begins and ends. With literal strings to use a double quote as part of the string all you have to do is put two double quotes together.
     //two double quotes are turned into one //literal double quote string sql= @"select * from contacts where " sql += @"lastname=  ""  Jones  ""  sql += @"and firstname=  ""  Indiana  ""  ; 
  • If you use literal strings you can split a string into multiple lines of code; however, keep in mind that doing so inserts a carriage return character into the string ( Figure 4.39 ).

    Figure 4.39 When you break a literal strings into multiple lines the carriage returns you put in the editor are preserved. However, they aren't visible in HTML because white space is condensed into a single space.
      string msg = @"Welcome to WidgetsUSA   First Bank of Cyberspace.   Your Balance is 00.";  txtMessage.Text = msg; //output: // Welcome to WidgetsUSA //           First Bank of Cyberspace. //           Your Balance is 00. Response.Write(msg); //output: //Welcome to WidgetsUSA First Bank of Cyberspace. Your Balance is 00. 
  • The rules for when white space is preserved, which we discussed in the previous section, also apply to literal strings.




C#
C# & VB.NET Conversion Pocket Reference
ISBN: 0596003196
EAN: 2147483647
Year: 2003
Pages: 198
Authors: Jose Mojica

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net