Create An Array Of String In C#
Code snippet for how to Create An Array Of String In C# with sample and detail explanation
C# is a widely used programming language that provides a broad range of features. Among its features is the ability to create an array of strings, which can come in handy in various programming scenarios.
Code Snippet: Creating An Array Of String In C#
using System;
class Program
{
static void Main()
{
string[] stringArray = {"Hello", "World", "Array", "String"};
Console.WriteLine("Array Elements : ");
foreach(string word in stringArray)
{
Console.WriteLine(word);
}
}
}
Code Explanation for Creating An Array Of String In C#
In this C# program, we have created an array of strings. The step-by-step explanation for this code is as follows:
-
The
using System;
command is a preprocessor directive that includes the System namespace in our program. This namespace in C# contains fundamental classes and base classes that define commonly-used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions. -
We then declare our main class,
Program
, and within this main class, we define our main function,Main()
. The Main method is the entry point of a C# console application or windows application. -
Inside the
Main()
method, we define an array of strings with the namestringArray
and initialize it with four string elements: “Hello”, “World”, “Array”, “String”. -
Now, to print each word present in the array, we use a
Console.WriteLine
statement, which writes the specified string value or object to the standard output stream. We use this inside aforeach
loop to iterate through each item in the array. -
Each iteration of the loop takes an item from the
stringArray
, assigns it to the variableword
, and then executes the loop’s body (which in this case isConsole.WriteLine(word);
). -
After writing the output, the program ends and control is returned to the operating system.
When you compile and execute the program, you’ll see the array’s elements printed one-by-one in the console.