Constructing Strings


The simplest way to construct a string is via a string literal. For example, an object of the class string may be formed as follows.

string s = "Hello world";

The string object s is initialized from the quoted string literal "Hello world". Strings may also be created from a character array. For example, the following is valid.

char[] a = {'H','e','l','l','o',' ','w','o','r','l','d'};
string s = new string(a);

Clearly, anywhere a string literal can be used, an object of the string class can be used in its place. For example, two strings are written to the console in the next program. Mostly string literals have been used as the argument of Console.WriteLine; here an object of class string is used instead.

// String1 - Objects of class string

using System;

class Program
{
    static void Main()
    {
        char[] a = { 'H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd' };
        string s = new string(a);

        Console.WriteLine(s);

        string hello = "Hello world";

        Console.WriteLine(hello);

    }
}

The output of the program is as follows.

Hello world
Hello world