String Assignment
String, how shall I make thee: let me count the ways. There are many ways to create string
variables, and if you’ve started working with C# you’ve probably used most of them.
But let’s go over this familiar ground one more time.
First, and most obviously, you can create a string by assigning a literal to a string variable:
string str = "I am a string!";
By the way, you can—of course—declare a string variable without initializing it:
string str;
As I showed you in the first part of this article, attempting to use this uninitialized variable
causes a compiler error (since definite assignment is required). What you may not know is that a
string variable, since it is a reference type, can be initialized to null:
string str = null;
Initializing a string to null is not the same as initializing it to an empty string:
string str = "";
In the case of the null assignment, no memory has been allocated for the string. An attempt
to determine the length of a null string—by using its Length property—causes an exception to
be thrown. In contrast, the Length property of an empty string is 0.
An alternate way to initialize an empty string is to use the static Empty field of the String
class:
string str = string.Empty;
|