TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# String Constructor

This C# example program uses the string instance constructor. It creates new strings.

String constructor. A string constructor call is normally not needed.

The C# language provides many string constructors. One possible use is creating a string containing one char repeated many times. Another is converting a char array into a string.

Tip: To create a new string, you usually should just modify an existing string or use a string literal.

String Literal

Example. Here we see the three simplest string constructors. These can be used in any code. They are not unsafe. The example demonstrates making a string from a char array, from a series of repeated letters, and from a char array range.

C# program that uses string constructors

using System;

class Program
{
    static void Main()
    {
	@A();
	@B();
	@C();
    }

    static void @A()
    {
	//
	// Create new string from char array.
	//
	char[] charArray = new char[3];
	charArray[0] = 'a';
	charArray[1] = 'b';
	charArray[2] = 'c';

	string exampleString = new string(charArray);
	Console.WriteLine(exampleString);
	Console.WriteLine(exampleString == "abc");
    }

    static void @B()
    {
	//
	// Create new string of repeated characters.
	//
	string exampleString = new string('a', 10);
	Console.WriteLine(exampleString);
	Console.WriteLine(exampleString == "aaaaaaaaaa");
    }

    static void @C()
    {
	//
	// Create new string from range of characters in array.
	//
	char[] charArray = new char[6];
	charArray[0] = 'a';
	charArray[1] = 'B';
	charArray[2] = 'c';
	charArray[3] = 'D';
	charArray[4] = 'e';
	charArray[5] = 'F';

	string exampleString = new string(charArray, 0, 3);
	Console.WriteLine(exampleString);
	Console.WriteLine(exampleString == "aBc");
    }
}

Output

abc
True

aaaaaaaaaa
True

aBc
True

The output of the program is shown in the bottom section. Each method displays the result string, and tests the string against a constant to see if the output is as expected, printing True.

True, False

First: Method @A shows how to use the string constructor that accepts a char array. This is an efficient way to perform this conversion.

Convert Char Array to String

Method @B demonstrates the string constructor that creates a series of a single characters. This is much simpler than using PadRight or PadLeft methods to create repeated characters. The example creates a string of ten 'a' letters.

PadRight, PadLeft

Method @C creates a string from a char array, as in method @A, but with a range. The example takes the character in the array at index 0, and then adds three chars. This is the equivalent of Substring, but acts on char arrays.

Substring

Note: We used the @ symbol on the method names as a way to make them stand out. You can use @ to specify identifiers of any name.

Constructors. To continue, we look at the eight string constructors in the .NET Framework. You can see that five of the constructors are unsafe. The three other constructors are shown in the example above.

String constructors: C#

unsafe public String(char*);
       public String(char[]);
unsafe public String(sbyte*);
       public String(char, int);
unsafe public String(char*, int, int);
       public String(char[], int, int);
unsafe public String(sbyte*, int, int);
unsafe public String(sbyte*, int, int, Encoding);

Unsafe string constructor methods. This article doesn't demonstrate the unsafe constructors, as your code should avoid unsafe methods. You might need these five unsafe methods for DLL interop.

Tip: There is no difference between calling "new String" and "new string". The uppercase first letter makes no difference.

Optimization. You can use the string constructors as an impressive optimization. Sometimes, you can entirely replace StringBuilder. This is most useful for sorting algorithms or other lower-level operations on strings in C# programs.

Char ArrayStringBuilder

Single chars: We can sometimes optimize the string constructor that repeats characters N times (method @B above) to a string literal.

Equivalent string constructor calls: C#

return new string('a', 5);
return "aaaaa";

Summary. String constructors are occasionally useful. We used the three string constructors in C# that are not unsafe. We examined the method signatures, discussed unsafe, and found ways strings can be optimized.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf