C# String Array

by Sam Allen - Updated January 7, 2010

You have a set of string values you need to store in a string array using the C# programming language. There are different ways of declaring arrays, and you want to see them. Here we see several different ways of declaring and using string arrays in the C# language.

Array

Declaring string arrays

First, here we see that there are several ways to declare and instantiate a string[] array local variable. They are all equivalent in the compiled code [see note], so choose the one you think is clearest to read.

~~~ Program that initializes string arrays (C#) ~~~

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

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

Description. The above Main function shows four string[] arrays, each equivalent to the compiler. The biggest difference is that the first three arrays are declared on one line, while the fourth array is assigned in separate statements. The fourth array would allow you to test each value or insert logic as you assign it.

Note. Internally, the above array initializations result in several MSIL instructions each. To create the array reference, "newarr string" is emitted, and then to assign each element the instruction "stelem" is used to set the elements.

String arrays at class level

Here we see ways to use string[] arrays as fields or properties in classes. This is useful for storing values, either statically or in instances. You can also return string arrays with methods. String elements can also be returned with an indexer.

=== Program that uses string array (C#) ===

class Program
{
    static void Main()
    {
        Test test = new Test(); // Create new instance with string array
        foreach (string element in test.Elements) // Loop over elements with property
        {
            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 of the program ===

one
two
three

one

Description. The first part of the code is the Main method, which is the program entry point. A new instance of the Test class is created. Internally, that class contains an array of strings. The Test class would in real-life modify its internal strings.

Test class. The Test class contains a string array field. The elements in the array are actually added in the constructor for the class, which the C# compiler generates for you automatically.

Elements property. The second part of the Test class is a property accessor. It provides a clean way for external code to access the internal array. Properties are not useful in many cases, but in some systems can help.

The this[int] code. The final part of the Test class is called an Indexer. This is basically a function that receives one parameter, an integer, and returns a value based on that parameter. You can duplicate this with a method.

(See Indexer Example.)

Empty string array property

As you will see on the MSDN array usage guidelines, returning a null string array in a property can be confusing to callers and is therefore discouraged. We example this issue with array properties, and review MSDN, on a separate article on this site.

(See Array Property, Returning Empty Array.)

String arrays vs. other arrays

This document focuses on string arrays, and string arrays are different than other arrays in some ways. First, strings are the only data type you can declare with quoted values. Second, strings are reference types and can be null, unlike integers.

Using the concepts shown above. Even though strings and string arrays are different in their syntax, the general usage is the same and you could substitute int arrays or object arrays. You can find more information in the arrays category at this web site.

Loops

Here we note how you can loop over string arrays in your C# programs. There are two main ways to loop over string arrays: foreach and for. These are covered in depth in a separate article.

(See Loop Over String Array.)

Converting string arrays

One of the most common problems with string arrays is converting them to other types of arrays and strings. This site has more detailed information about converting string arrays to strings. You can also find how to convert char arrays and strings.

(See Convert String Array to String.)

Summary

Here we saw ways to use string arrays in C# programs. You can declare string arrays in several different ways, but often they are compiled to the same code. It is effective to use string arrays in return values and also in indexers. You can also avoid some complexity by returning empty string arrays instead of null references.

(Do not copy this page.)

Dot Net Perls | Search
Arrays | 2D Array Use | Byte Array | Char Array Use | Convert List to Array | Count Array Elements
C# | Integer.TryParse | ArrayList Examples | Bituminous Coal | Sleep Method Use
© 2009 Sam Allen. All rights reserved.
Dot Net Perls | Sam Allen