In C#, string
is a reference type, but it is compared by value when using ==.
// In this example, even if s and t are not referentially equal, they are equal by value:string s = "hello";string t = "hello";// b is truebool b = (s == t);
In C#, string
types are immutable, which means they cannot be changed after they are created.
// Two examples demonstrating how immutablility determines string behavior. In both examples, changing one string variable will not affect other variables that originally shared that value.//EXAMPLE 1string a = "Hello?";string b = a;b = "HELLLLLLLO!!!!";Console.WriteLine(b);// Prints "HELLLLLLLO!!!!"Console.WriteLine(a);// Prints "Hello?"//EXAMPLE 2string s1 = "Hello ";string s2 = s1;s1 += "World";System.Console.WriteLine(s2);// Prints "Hello "
In C#, a string
reference can refer to an empty string with ""
and String.Empty
.
This is separate from null
and unassigned references, which are also possible for string
types.
// Empty string:string s1 = "";// Also empty string:string s2 = String.Empty;// This prints true:Console.WriteLine(s1 == s2);// Unassigned:string s3;// Null:string s4 = null;