char, string and bool
char and its escapes
A char is one UTF-16 code unit in single quotes, and it is a number underneath: a cast to int gives the code point, and a cast back gives the character. The same program also shows the escapes.
char letter = 'A';
Console.WriteLine((int)letter);
Console.WriteLine((char)(letter + 2));
string text = "hello";
string upper = text.ToUpper();
Console.WriteLine(text);
Console.WriteLine(upper);
Console.WriteLine(text == "hello");
Console.WriteLine(object.ReferenceEquals(text, upper));
Console.WriteLine(letter == 'A' && !false);
Console.WriteLine("a\tb");
dotnet run
65
C
hello
HELLO
True
False
True
a b
The escapes a C# program needs are \n for a line break, \t for a tab, \ for a backslash, \" for a double quote inside a string, ' for a single quote inside a char and \u0041 for a character by its code.
A string is immutable
text.ToUpper() did not change text: it returned a new string. Every method of string works that way, which is why Replace, Trim and Substring have to be assigned to something:
string text = " hello ";
text.Trim();
Console.WriteLine($"[{text}]");
text = text.Trim();
Console.WriteLine($"[{text}]");
dotnet run
[ hello ]
[hello]
An immutable string is what makes it safe to pass one to any method: no callee can change it behind the caller. The cost is that a loop that concatenates a string builds a new one each time, which is the subject of StringBuilder.
== against ReferenceEquals
== on two strings compares their characters, because string defines the operator. On two other reference types it compares the references, which is the default of the language:
string a = new string('A', 3);
string b = "AAA";
Console.WriteLine(a == b);
Console.WriteLine(object.ReferenceEquals(a, b));
var boxA = new Box { X = 1 };
var boxB = new Box { X = 1 };
Console.WriteLine(boxA == boxB);
Console.WriteLine(boxA.Equals(boxB));
class Box
{
public int X;
}
dotnet run
True
False
False
False
The two strings hold the same characters but are two different objects, so == is true and ReferenceEquals is false. The two Box objects are equal in no sense: no operator and no Equals was written for them, so both comparisons ask about identity. The lesson on records shows the type that gets value equality for free, and operators and indexers shows how to write one.
bool and short-circuit
A bool is true or false, and the operators are &&, || and !. The first two short-circuit: the right side runs only when the left side does not decide the answer.
string? missing = null;
Console.WriteLine(string.IsNullOrEmpty(missing));
Console.WriteLine(char.IsDigit('7'));
Console.WriteLine("Ada".StartsWith("A"));
Console.WriteLine(string.Compare("a", "b"));
Console.WriteLine(true || Fail());
Console.WriteLine(false && Fail());
static bool Fail()
{
Console.WriteLine("not reached");
return true;
}
dotnet run
True
True
True
-1
True
False
not reached never printed: the left side of true || is already true, and the left side of false && is already false. That is why a null check and a dereference live in one expression: name is not null && name.Length > 0 is safe, while name.Length > 0 & name is not null is not: the single & and | evaluate both sides.
Exercises
- Print the code point of 'z' and the character with code 955. What is it?
- Call Trim() without assigning the result and print the string. Why is it unchanged?
- Compare two strings built by new string(...) with == and with ReferenceEquals. Which is true?
- Change true || Fail() to true | Fail() and run it. Which line appears now?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does this program print?
char letter = (char)65; Console.WriteLine(letter);Answer
A
Code 65 is the capital A, so the cast to char prints the character rather than the number.
-
What happens when the result of Trim() is not assigned?
Answer
Nothing changes, because a string is immutable and Trim returns a new one
Every string method returns a new string; a call whose result is dropped has no effect at all.
-
What does this program print?
string a = "hello"; string b = a.ToUpper(); Console.WriteLine(a); Console.WriteLine(b);Answer
hello / HELLO
ToUpper returns a new string and leaves a alone, so the first line keeps the lower case.
-
What does
==compare on two strings?Answer
Their characters, because string defines the operator
string overloads the equality operators to compare the text, which is why two different objects can be ==.
-
What does this program print?
string a = new string('A', 3); string b = "AAA"; Console.WriteLine(a == b); Console.WriteLine(object.ReferenceEquals(a, b));Answer
True / False
The two strings hold the same characters but are different objects, so == is true and ReferenceEquals is false.
-
What does this program print?
Console.WriteLine(false && SideEffect()); Console.WriteLine(true || SideEffect()); static bool SideEffect() { Console.WriteLine("called"); return true; }Answer
False / True
Both && and || short-circuit, so the right side never runs and the only output is the two booleans.
-
Which operator evaluates both sides of a bool expression?
Answer
The single &
The single & and | are the non-short-circuit forms, and only && and || skip the right side.
-
What does this program print?
Console.WriteLine((int)'A' + 1); Console.WriteLine((char)((int)'A' + 1));Answer
66 / B
The first line adds to the code point and prints it, and the second casts the sum back to a character.
-
What does this program print?
Console.WriteLine("a\tb".Length);Answer
3
The escape becomes one tab character, so the string holds a, the tab and b, three characters in all.
-
What does char store?
Answer
One UTF-16 code unit, which is a number with a character form
char is a 16-bit number that a cast can read or write; a character outside the basic plane needs two chars.
The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev