#7 – C# string type

In this short tutorial, you will learn the key points of string and String type in C#.

Concept

C# recognizes the string keyword, which under the hood is translated to the .NET class System.String whose value is text. Internally, the text is stored as a sequential read-only collection of Char objects.

In C#, the string keyword is an alias for String. Therefore, String and string are equivalent, and you can use whichever naming convention you prefer.

Immutable

string is a reference type. Behind the scenes, a string object is allocated on the heap, not the stack;
But String objects are immutable which means they cannot be changed after they have been created.

using System;

string str1 = "Hello World";
string str2 = str1;

Console.WriteLine($"str1: {str1}; str2: {str2};");

str1 = "Bye Bye";
Console.WriteLine($"str1: {str1}; str2: {str2};");

Output:

str1: Hello World; str2: Hello World;
str1: Bye Bye; str2: Hello World;

All of the String methods and C# operators that appear to modify a string actually return the results in a new string object.

For example, when you assign one string variable to another string, you get two references to the same string in memory. But strings are immutable, making changes to one of these strings creates an entirely new string object, leaving the other string unchanged.

Verbatim String Literals

Use verbatim strings for convenience and better readability when the string text contains backslash characters, for example in file paths.

You can prefix a string literal with the at character (@) and all the characters after it are treated at face value; they aren’t interpreted as escape sequences

using System;

string filePath1 = "C:\\Users\\CoderCMS\\Documents\\";
string filePath2 = @"C:\Users\CoderCMS\Documents\";

Console.WriteLine($"file path 1: {filePath1}");

Console.WriteLine($"file path 2: {filePath2}");

Output:

file path 1: C:\Users\CoderCMS\Documents\
file path 2: C:\Users\CoderCMS\Documents\

String Interpolation

Available in C# 6.0 and later, interpolated strings are identified by the $ special character and include interpolated expressions in braces.

using System;

string description = "Hello World";
int age = 20;

Console.WriteLine($"description: {description};");
Console.WriteLine($"age > 10 ?: {age > 10};");

Output:

description: Hello World;
age > 10 ?: True;

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.