C# String Array

Array

String array. Strings sometimes need to be stored together. One way to do this is with a string array. Several syntax forms are used to declare and create string arrays.

Strings
Syntax

Syntax. String array syntax forms are often compiled into equivalent code. So we can choose the syntax that is simplest for a program.


String array

Four example arrays. Square brackets are used for all arrays, including string arrays. The syntax is fairly simple, but we need to memorize it (as in all programming languages).

Note:All of these constructs are equivalent in the compiled code. Please choose the one you think is clearest.

Var:The var type is an implicitly-typed local variable. It is the same to the compiler as an explicit string array.

Var

Tip:The fourth array allows us to test each value or insert logic as we assign it. This is sometimes useful.

Based on:

.NET 4.5

Program that initializes string arrays: C#

class Program
{
    static void Main()
    {
	// String arrays with 3 elements:
	string[] arr1 = new string[] { "one", "two", "three" };
	string[] arr2 = { "one", "two", "three" };
	var arr3 = new string[] { "one", "two", "three" };

	string[] arr4 = new string[3];
	arr4[0] = "one";
	arr4[1] = "two";
	arr4[2] = "three";
    }
}
Field

Fields. We use string arrays as fields (or properties) in classes.
This is useful for storing values,
either statically
or in instances. We can also return string arrays.

In Main:A new instance of the Test class is created. That class contains an array of strings.

Program that uses string array in class: C#

class Program
{
    static void Main()
    {
	// Create new instance with string array.
	Test test = new Test();

	// Loop over elements with property.
	foreach (string element in test.Elements)
	{
	    System.Console.WriteLine(element);
	}
	System.Console.WriteLine(test[0]); // Get first string element
    }
}

public class Test
{
    /// <summary>
    /// String array field instance.
    /// </summary>
    string[] _elements = { "one", "two", "three" };

    /// <summary>
    /// String array property getter.
    /// </summary>
    public string[] Elements
    {
	get { return _elements; }
    }

    /// <summary>
    /// String array indexer.
    /// </summary>
    public string this[int index]
    {
	get { return _elements[index]; }
    }
}

Output

one
two
three
one
This keyword

Above, the Test class contains a string array field. The elements in the array are added in the constructor for the class. The C# compiler generates this code automatically.

Elements:The second part of the Test class is a property accessor. It provides a clean way for external code to access the internal array.

Indexer:The final part of the Test class is called an Indexer. An indexer uses the this-keyword.

Indexer

Note:The indexer shown receives one parameter, an integer, and returns a value based on it.


Net

IL instructions. C# programs are compiled into IL instructions. String array initializations result in several instructions. To create the array reference, "newarr string" is emitted.

And:To assign each element the instruction "stelem" is used. For static arrays, a separate opcode is generated.

newarr Instructionstelem Instruction
Property

Null property. As we see on MSDN's array usage guidelines, returning a null string array in a property can be confusing to callers. It is therefore discouraged.

Array Property
Squares: abstract

Types. String arrays are different from other arrays. Strings are the only data type we declare with quoted values. Also, strings are references and can be null, unlike integers.

Null

However:Even though strings and string arrays are different in their syntax, the general usage remains the same.

Convert:A common problem with string arrays is converting them to other types of arrays and strings. Custom methods are often used.

Convert Array, String
Loop

Loops. We can loop over string arrays in programs. We see the foreach-loop on this page, but other loops (for, while, even "do") are options.

Loop, String ArrayForeachFor
Main method

String args. When a C# program is started, an optional string array is received from the operating system. This array, args, contains string arguments.

Args Loop

Tip:The args array is empty when no arguments are passed. Try creating a shortcut in Windows to your C# executable.

Here:I added the argument string "hello world" to the command in the Windows shortcut. The two strings are received into the args array.

Program that uses args string array: C#

using System;

class Program
{
    static void Main(string[] args)
    {
	// ... Loop over arguments passed to this program.
	foreach(string value in args)
	{
	    Console.WriteLine("Argument: {0}", value);
	}
	Console.ReadLine();
    }
}

Output

Argument: hello
Argument: world
Split

Join, Split. The string.Join() method receives a string array and combines the strings into one. And Split() separates strings that a rejoined together with a delimiter char.

Join:This example uses the Join method to combine the three string literals within the "elements" array.

Join

Split:Finally we invoke Split to change our joined string back into a string array. The two string arrays are separate in memory.

Split
Program that uses Join, Split: C#

using System;

class Program
{
    static void Main()
    {
	string[] elements = { "cat", "dog", "fish" };
	Console.WriteLine(elements[0]);

	// ... Join strings into a single string.
	string joined = string.Join("|", elements);
	Console.WriteLine(joined);

	// ... Separate joined strings with Split.
	string[] separated = joined.Split('|');
	Console.WriteLine(separated[0]);
    }
}

Output

cat
cat|dog|fish
cat
The C# programming language

String arrays are declared in many syntax forms. We commonly use string arrays in return values and in indexers. A good technique is to return empty string arrays.


Upon startup, a program receives an optional string array. This array type is essential to C# programs. An understanding of string arrays, too, is key.


C#: Array