Login

Username:

Password: 

Join us Now |  Forgot Password? | Forgot UserName?

Blogs


C# 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. They are often compiled into equivalent code.

Example

There are several ways to declare and instantiate a string array local variable. We show them. In the C# language, a string array is of type string[]. The reference can be null or assigned to a new string[]. Square brackets are used.

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";

    }

}

Result

 Four string arrays are initialized.

 

 Program that uses string array: 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; }

    }

    public string this[int index]

    {

get { return _elements[index]; }

    }

}

 

Output

one

two

three

 

one



Your comment