C# / CHAPTER 02
Values, types, and strings
BeginnerPredict expression results before choosing a variable type.
By the end of this chapter
- Use inferred and explicit types
- Distinguish integer division from decimal arithmetic
- Transform immutable strings
The idea
C# assigns a type to every variable. var asks the compiler to infer that type from the initializer; it does not make the variable dynamically typed. Whole-number literals normally produce int values, while a suffix such as m creates a decimal literal. Choose the numeric representation from the problem, and remember that integer division discards its fractional part before assignment.
Strings provide methods for transformations and properties such as Length for inspection. Their contents are immutable, so a transformation returns a value instead of editing the receiver. Interpolation places expressions inside a readable string template. These examples use ASCII text so character positions and displayed characters line up predictably.
using System;
var completed = 9;
var days = 4;
string label = " draft ";
Console.WriteLine(completed / days);
Console.WriteLine($"[{label.Trim()}]");2 [draft]
Both operands of division are integers, producing two. Trim returns a new string; interpolation adds the visible brackets around that result.
Try it yourself
Build a label containing a trimmed project name and its character count.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING