How To Declare and access array of string in C#

How To Declare and access array of string in C#

Here we will see how to declare an array of string and access it's elements using for loop. Example uses both C#.net and VB.net programs.

C# declare an array of strings.

String Array Example.

Let's see C# program to declare an access array of strings. It declares and retrieve fourth element of array

using System;
namespace Csharp.ArrayOfStrings
{
class Program
{
static void Main(string[] args)
{
string[] arrayOfStrings = new string[] { "C#", "Dotnet",
"Examples","Declare" , "Array", "Of", "Strings" };
int length = arrayOfStrings.Length;
Console.WriteLine("Fourth element of array is {0}",arrayOfStrings[4]);
for (int index = 0; index < length; index++)
{
Console.WriteLine("String at position number {0} is {1}.", index, arrayOfStrings[index]);
}
Console.ReadLine();
}
}
}

VB.net code declare and access array of strings

VB.net Program

VB.net Example declares an array of strings and retrieves fourth element of it.

Namespace Csharp.ArrayOfStrings
Class Program
Private Shared Sub Main(args As String())
Dim arrayOfStrings As String() = 
New String() {"C#", "Dotnet", "Examples", "Declare", "Array", "Of", _ "Strings"} Dim length As Integer = arrayOfStrings.Length Console.WriteLine("Fourth element of array is {0}", arrayOfStrings(4)) For index As Integer = 0 To length - 1 Console.WriteLine("String at position number {0} is {1}.", index, arrayOfStrings(index)) Next Console.ReadLine() End Sub End Class End Namespace
Output
Fourth element of array is Array
String at position number 0 is C#.
String at position number 1 is Dotnet.
String at position number 2 is Examples.
String at position number 3 is Declare.
String at position number 4 is Array.
String at position number 5 is Of.
String at position number 6 is Strings.

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5