String constructor. Usually a string constructor call is not needed. But the C# language has many string constructors. These create strings from characters and arrays.
One possible use for a string constructor is creating a string containing one char repeated many times. Another is converting a char array into a string.
Char array example. To begin, we show how to create a string from a char array. The string constructor in C# is useful for creating strings from various data sources.
Part 1 We create a 3-element char array. It is at first empty, but we assign 3 characters to its memory.
using System;
// Part 1: create char array.
char[] charArray = new char[3];
charArray[0] = 'a';
charArray[1] = 'b';
charArray[2] = 'c';
// Part 2: create string from array.
string exampleString = new string(charArray);
Console.WriteLine(exampleString);
Console.WriteLine(exampleString == "abc");abc
True
Repeated chars. Suppose we want to create a whitespace string with a space repeated 100 times. This is easy with the string constructor—no large string literal is needed.
Here We repeat the letter "A" 10 times. The resulting string can be used like any other in a C# program.
using System;
// Create new string of repeated characters.
string exampleString = new string('a', 10);
Console.WriteLine(exampleString);
Console.WriteLine(exampleString == "aaaaaaaaaa");aaaaaaaaaa
True
Char array, range. Suppose we have a char array, but want to create a string from just part of it. We can use another string constructor and specify and offset or a length.
Here We start at index 0, and continue until we have taken 3 chars. We turn the first 3 chars of the array into a string.
using System;
// 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");aBc
True
Optimization. We can use the string constructors as an impressive optimization. Sometimes, we can entirely replace StringBuilder with a char array.
And This is most useful for sorting algorithms or other lower-level operations on strings in C# programs.
String constructors are occasionally useful. We used the 3 string constructors in C# that are not unsafe. And we found ways string conversions can be optimized.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on May 11, 2023 (simplify).