Hit enter after type your search item

Creating string array in C#

A string array in C# can be created, initialized, and assigned values as described below.

Declaring a string type array:

string[] strArr;

Initializing the string array:

As array in C# is a reference type, the new keyword is used to create an array instance:

string[] strArr = new string[5];

Assigning values at the time of declaration:

string[] strArrCities = new string[] { “New York”, “London”, “Berlin”, “Paris”, “Dubai” };

You may also assign values as follows:

The examples below shows declaring, initializing and accessing string arrays in different ways.

An example of a string array

In this example, an array is declared and initialized without specifying the array size. The values are also assigned at the time of declaration. Then, a foreach loop is used to iterate through the array elements and displaying values:

c# string-array

Declaring a string array with size example

In this string array example, we have declared an array of five size. After declaration, the values are assigned by using the index number and then foreach loop is used to display array elements:

c# string-array-animals

Using for loop to iterate through a string array

The example below shows using a for loop to iterate through the array elements and displaying on the screen. For the condition part of the for loop, I used the length property of Array as follows:

How to convert a string array to string

One of the ways for converting an array to string is using the join method. The join is the method of string class where you may specify the array as shown in the example below:

The output of the above code is:

This is String Array Tutorial

This div height required for enabling the sticky sidebar