String.Join Method (String, Object[])
[ This article is for Windows Phone 8 developers. If you’re developing for Windows 10, see the latest documentation. ]
Concatenates the elements of an object array, using the specified separator between each element.
Assembly: mscorlib (in mscorlib.dll)
Parameters
- separator
- Type: System.String
The string to use as a separator.
- values
- Type:
System.Object
[]
An array that contains the elements to concatenate.
Return Value
Type: System.StringA string that consists of the elements of values delimited by the separator string. If values is an empty array, the method returns String.Empty.
| Exception | Condition |
|---|---|
| ArgumentNullException | values is null. |
If separator is null, an empty string (String.Empty) is used instead. If any element of values other than the first element is null, an empty string (String.Empty) is used instead.
Join(String, Object[]) is a convenience method that lets you concatenate each element in an object array without explicitly converting its elements to strings. The string representation of each object in the array is derived by calling that object's ToString method.
Notes to CallersIf the first element of values is null, the Join method does not concatenate the elements in values but instead returns String.Empty. A number of workarounds for this issue are available. The easiest is to assign a value of String.Empty to the first element of the array, as the following example shows.
The following example uses the Sieve of Eratosthenes algorithm to calculate the prime numbers that are less than or equal to 100. It assigns the result to a integer array, which it then passes to the Join(String, Object[]) method.
using System; using System.Collections.Generic; public class Example { public static void Demo(System.Windows.Controls.TextBlock outputBlock) { int maxPrime = 100; int[] primes = GetPrimes(maxPrime); outputBlock.Text += String.Format("Primes less than {0}:", maxPrime) + "\n"; outputBlock.Text += String.Format(" {0}", String.Join(" ", primes)) + "\n"; } private static int[] GetPrimes(int maxPrime) { int[] values = new int[maxPrime + 1]; // Use Sieve of Erathsthenes to determine prime numbers. for (int ctr = 2; ctr <= (int)Math.Ceiling(Math.Sqrt(values.GetUpperBound(0))); ctr++) { if (values[ctr] == 1) continue; for (int multiplier = ctr; multiplier <= maxPrime / 2; multiplier++) if (ctr * multiplier < maxPrime + 1) values[ctr * multiplier] = 1; } List<int> primes = new List<int>(); for (int ctr = 2; ctr <= values.GetUpperBound(0); ctr++) if (values[ctr] == 0) primes.Add(ctr); return primes.ToArray(); } } // The example displays the following output: // Primes less than 100: // 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97