string
String
Declaring and initializing strings
// Declare without initializing.
string message1;
// Initialize to null.
string? message2 = null;
// Initialize as an empty string.
// Use the Empty constant instead of the literal "".
string message3 = System.String.Empty;
// Initialize with a regular string literal.
string oldPath = "c:\\Program Files\\Microsoft Visual Studio 8.0";
// Initialize with a verbatim string literal.
string newPath = @"c:\Program Files\Microsoft Visual Studio 9.0";
// Use System.String if you prefer.
System.String greeting = "Hello World!";
// In local variables (i.e. within a method body) you can use implicit typing.
var temp = "I'm still a strongly-typed System.String!";
// Use a const string to prevent 'message4' from being used to store another string value.
const string message4 = "You can't get rid of me!";
// Use the String constructor only when creating a string from a char*, char[], or sbyte*. See System.String documentation for details.
char[] letters = { 'A', 'B', 'C' };
string alphabet = new string(letters);
NOTE:
To prevent NullReferenceException errors, initialize strings using the string.Empty constant (or "") instead of null. This creates a valid string object with zero length. Before accessing a string, use the string.IsNullOrEmpty() method to safely check its state.
Key Takeaways:
- Avoid null: Use
string.Emptyto ensure the object exists. - Literal Form: The value is represented as "".
- Safety First: Use
string.IsNullOrEmpty(yourString)as a defensive coding practice to verify values before use.
Immutability of strings
string s1 = "A string is more ";
string s2 = "than the sum of its chars.";
// Concatenate s1 and s2. This actually creates a new string object and stores it in s1, releasing the reference to the original object.
s1 += s2;
System.Console.WriteLine(s1);
// Output: A string is more than the sum of its chars.
string str1 = "Hello ";
string str2 = str1; // refrence of string
str1 += "World"; // modified string create new ref for str1;
System.Console.WriteLine(str2);
//Output: Hello
Quoted string literals
string columns = "Column 1\tColumn 2\tColumn 3";
//Output: Column 1 Column 2 Column 3
string rows = "Row 1\r\nRow 2\r\nRow 3";
/* Output:
Row 1
Row 2
Row 3
*/
string title = "\"The \u00C6olean Harp\", by Samuel Taylor Coleridge";
//Output: "The Æolean Harp", by Samuel Taylor Coleridge
string filePath = @"C:\Users\scoleridge\Documents\";
//Output: C:\Users\scoleridge\Documents\
string text = @"My pensive SARA ! thy soft cheek reclined
Thus on mine arm, most soothing sweet it is
To sit beside our Cot,...";
/* Output:
My pensive SARA ! thy soft cheek reclined
Thus on mine arm, most soothing sweet it is
To sit beside our Cot,...
*/
string quote = @"Her name was ""Sara.""";
//Output: Her name was "Sara."
Comments
Post a Comment