May 18, 2015

C# Different ways to create a string

Strings, in C#, represents text as a series of Unicode characters. A string can be referenced as both "string" and "String" - string is basically an alias of System.String.  It can be created in a number of ways. In the simplest form, it can just be assigned or alternatively it can be created using the String's constructors. String, like other objects in .NET, can be assigned to null. Strings might look like and can be used like other variables like int or double but one important characteristics is that it is immutable - that is, once a String is created, it cannot be changed (so, when a string variable is re-assigned, behind the scenes, a new string is created and assigned to the variable).

Here is an example of different way of how strings can be created.

public void CreateString()
{
    string str1 = "Some text";
    string str2 = @"some text with filename C:\folder\filename.txt";
    string str3 = "text with \n new line";
    string str4 = ""; //empty string
    string str5 = string.Empty; //empty string
    string str6 = new string('S', 5); //SSSSS
    string str7 = new string(new char[]{ 'A', 'B', 'C', 'D', 'E' });
    string str8 = null;

    char[] list = { 'A', 'B', 'C', 'D', 'E' };

}

0 comments:

Reference: Shahed Kazi at AspNetify.com