Strings

Strings

A string is an object of type String whose value is text. Internally, the text is stored as a sequential read-only collection of Char objects.

The Length property of a string represents the number of characters in contains

String Alias

In C#, the string keyword is an alias for String. Therefore, String and string are equivalent, regardless it is recommended to use the provided alias string as it works even without using System;

Usage

string myString = "A string";
String myString = "A string";
string emptyString = String.Empty;
string anotherEmptyString = "";

Concatenation

string sentence = "I like to play ";
sentence += "chess.";
Console.WriteLine(sentence);

Exercise

Expectation

String formatting and interpolation

To format a string to make it appear the way we want, we have many ways:

  • Simply concatenate all the strings with a + operator (less readable and error prone)

  • Use String.Format() (Good option in most cases)

  • Use string interpolation (Modern approach and more readable code)

Exercise

Expectation

Last updated