Indexer operator []
- Last UpdatedApr 24, 2024
- 1 minute read
Indexer operator, [], is used for strings, lists and dictionaries to access a specified element.
An IndexOutOfRangeExeption is thrown when an array index is outside the bounds of the dimension of the object.
Example code
string q="1 2 3 4";
string q2="first number: "+q[0]+" second number: "+q[2]; // first number: 1 second number: 2
List<int> a = { 1,2,3,4 };
a[0] = 10; //a={10,2,3,4}
Dictionary<string, string> dict = { {"key1","value1"},{"key2","value2"} };
int keyLength= dict.Keys[0].Length; //keyLength=4;
Runtime::Environment.Print("key1: "+dict["key1"]); //key1: value1
Runtime::Environment.Print("first letter of second key is "+dict.Keys[1][0]); //first letter of second key is g