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

Enter your name!
Ravi
Welcome Mr/Ms. Ravi
using System;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Enter your name!");
        string name = Console.ReadLine();
        
        Console.WriteLine();//todo 
    }
}

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)

int x = 1, y = 2;
int sum = x + y;

//Use String.Format()
string sumCalculation = String.Format("{0} + {1} = {2}", x, y, sum);
Console.WriteLine(sumCalculation);

//Or, use Interpolation
sumCalculation = $"{x} + {y} = {sum}";
Console.WriteLine(sumCalculation);

Exercise

Expectation

Enter your name
Raj
Enter your age
29
Hello Raj!! Hope you are having a good day!
You will be 30 years old by 2023!
using System;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Enter your name");
        string name = Console.ReadLine();

        Console.WriteLine("Enter your age");
        int age = Convert.ToInt32(Console.ReadLine()) ;

        string msg = String.Format(); //todo - using Format() method
        Console.WriteLine(msg);

        int nextAge = age +1;
        int nextYear = 2023;
        msg = $""; //todo  - using interpolation
        
        Console.WriteLine(msg);
    }
}

Last updated