C# Strings with Examples

A series of characters is used to store the text type data. It can be a character or a long paragraph. A string type variable can be defined as the below example.

string Student_Name = "Shahzad";
// OR
string Student_Info = "Shahzad Hussain Student of C#";

The size of the string can be a maximum of 2GB or 1 billion characters. But practically it totally depends on the memory of the computer and CPU.

In C# string also be initialize with char keyword because it’s the collection of characters or an array of characters.

Example:

using System;

namespace ConsoleApp1
{  
    class Program
    {
       //Char Type String
       static unsafe void Main(string[] args)
        {
            char[] alphabatic = { 'H', 'e', 'l', 'l', 'o' };
            string getvalue = new string(alphabatic);          
            foreach (char charac in getvalue)
            {
                Console.WriteLine(charac);
            }
        }
    }
}

A string can contain any type of special character because it is surrounded by () but we cannot add “in the string because it’s a compile-time error

We use @ character before the “it indicates that this is a multiline string.

String Concatenation

For the concatenation of string, we use the + sign between multiple strings.

Example:

using System;

namespace ConsoleApp1
{  
    class Program
    {
       //Concatenation of string
       static unsafe void Main(string[] args)
        {
            string Student_Name = "Shahzad" + " Hussain " + " Malik";           
            Console.WriteLine(Student_Name);
        }
    }
}

As you know String is immutable in C#, once it is created in the memory, the string can't be changed and it is read-only. When you concatenate a string every time, .NET CLR will create a memory location for the concatenated string. So it is recommended to use StringBuilder if you want to concatenate the multiple string values.

String Interpolation

String interpolation is the best way to concatenating. We use the + symbol for concatenating string variables with static strings. C #  includes a special $ character to identify the interpolated string. interpolated string character unit is a combination of a static string and a string variable where the string variable should be {} in brackets.

Example:

 using System;

namespace interpolationexample
{
    class Program
    {
        static void Main(string[] args)
        {
            string Student_Name = "Shahzad Hussain";
            string Name = $"MR. {Student_Name} !";
            Console.WriteLine(Name);
        }

    }
}