Strings and String Operations
Explore how to create and manipulate strings in C# including understanding immutability, performing efficient comparisons, combining text with interpolation, searching substrings, trimming unwanted characters, and modifying string content. This lesson provides practical techniques to handle text data effectively in .NET applications.
The string type is an alias for the System.String class. It is an immutable data type that represents a sequence of Unicode characters:
string someText = "Hello World!";
Here, we declare a string variable and assign it a standard text literal. We must account for string immutability when designing our applications. Immutable means that we cannot change the string. When we want to modify a string object, we just create a new one.
Instead of changing a property of an existing string object, the runtime creates a new object with the modified value. Remember that creating a new object involves allocating memory for that object.
Note: Constantly allocating memory for new class instances may significantly degrade application performance.
Be aware of this fact before generating strings.
Create strings
The System.String is a class. We have several approaches at our disposal to instantiate it. Modern C# allows us to execute this logic immediately using top-level statements. This reduces unnecessary boilerplate code.
Line 2: We create a string by assigning a direct literal value.
Line 6: We create a string by passing an array of characters to the string constructor. We utilize modern collection expression syntax for the array.
Because System.String is a class, it is a reference type. Therefore, we can assign null to a System.String variable. We use the nullable reference type syntax (?) to ensure strict compiler safety in modern .NET.
string? someString = null;
Here, we declare a nullable string type and assign a null value to indicate the absence of data.
Checking for empty strings
When working with text, we frequently need to verify if a string actually contains meaningful data. Instead of manually checking for null or a length of zero, modern C# provides two highly optimized static methods: string.IsNullOrEmpty() and string.IsNullOrWhiteSpace().
Lines 1–3: We define three variables representing common missing data scenarios.
Line 6: We use
IsNullOrEmptyto safely check thenullStringwithout causing a runtime error.Line 9: We use
IsNullOrWhiteSpaceto checkspaceString. This is the preferred method for user input because it treats strings filled only with spaces as empty.
Verbatim and raw string literals
Modern C# provides advanced string literals to handle escape characters and multi-line text efficiently. We use the @ symbol to create verbatim strings. Verbatim strings ignore ...