C# string create and initialize example

In this source code example, we show you different ways to create and initialize strings in C#.

There are multiple ways of creating strings, both immutable and mutable. We show a few of them.

C# string initialization examples

1. The most common way is to create a string object from a string literal:
string lang = "C#";
string ide = "Eclipse";

2. We create a string object from an array of characters:

char[] cdb = { 'M', 'y', 'S', 'q', 'l' };
string db = new string(cdb);

3. A StringBuilder object is created from a String:

var sb1 = new StringBuilder(lang);

Here is the complete example that shows a few ways of creating a System.String and System.Text.StringBuilder objects.:

using System;
using System.Text;

namespace MyApplication
{
  class Program
  {
    static void Main(string[] args)
    {
     	    char[] cdb = { 'M', 'y', 'S', 'q', 'l' };

            string lang = "C#";
            string ide = "Eclipse";
            string db = new string(cdb);
            
            Console.WriteLine(lang);
            Console.WriteLine(ide);
            Console.WriteLine(db);
            
            var sb1 = new StringBuilder(lang);
            var sb2 = new StringBuilder();
            
            sb2.Append("Source");
            sb2.Append(" Code ");
            sb2.Append("Examples");
            
            Console.WriteLine(sb1);
            Console.WriteLine(sb2);
     }
  }
}

Output:

C#

Eclipse

MySql

C#

Source Code Examples

Comments