C# String Array
1. Declaring string arrays
~~~ Program that initializes string arrays (C#) ~~
class Program
{
static
void Main()
{
//
String arrays with 3 elements:
string[]
arr1 = new string[] { "one", "two", "three" }; //
1
string[]
arr2 = { "one", "two", "three" }; // 2
var
arr3 = new string[] { "one", "two", "three" }; //
3
string[]
arr4 = new string[3]; // 4
arr4[0]
= "one";
arr4[1]
= "two";
arr4[2]
= "three";
}
}
Output of the program
(Four string arrays are initialized.)
2. String arrays at class level
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
{
/// String array field instance.
string[] _elements = { "one", "two", "three" };
string[] _elements = { "one", "two", "three" };
/// String array property getter.
public string[] Elements
public string[] Elements
{
get { return
_elements; }
}
/// String array indexer.
public string this[int index]
public string this[int index]
{
get { return
_elements[index]; }
}
}
Output of the program
one
two
three
one
Comments
Post a Comment