Example. Here we see a method that deals with char arrays and the new string constructor. When you need to build a string char-by-char, you should use a char array for best performance.
using System;
class CharTool
{
/// <summary>
/// Combine four chars.
/// </summary>
public static string CharCombine(char c0, char c1, char c2, char c3)
{
// Combine chars into array
char[] arr = new char[4];
arr[0] = c0;
arr[1] = c1;
arr[2] = c2;
arr[3] = c3;
// Return new string key
return new string(arr);
}
}
class Program
{
static void Main()
{
char a = 'a';
char b = 'b';
char c = 'c';
char d = 'd';
char e = 'e';
// Use CharCombine method
Console.WriteLine(CharTool.CharCombine(a, b, c, d));
Console.WriteLine(CharTool.CharCombine(b, c, d, e));
}
}abcd
bcde
Benchmark. The alternative here is the string.Concat method, which you can use with "+" between the 5 chars with ToString(). It is much slower and does unnecessary things.
Summary. We allocated a char array as a buffer to store 4 chars. You can easily adapt the method to handle two, three, five, or even more chars, and it will likely perform well.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 14, 2022 (grammar).