Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
C# [] Operator - Arrays and indexers
Code, Cosplay and Game - www.amiedd.com
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using System;
class PotionStrength 
{
   // Array of Potion Strength values
    private float[] potions = new float[10] { 56.2F, 56.7F, 56.5F, 56.9F, 58.8F, 
                                            61.3F, 65.9F, 62.1F, 59.2F, 57.5F };
    public int Length
    {
        get { return potions.Length; }
    }
    // Declare index.
    // If index is out of range, the potions array will throw the exception.
    public float this[int index]
    {
        get
        {
            return potions[index];
        }
        set
        {
            potions[index] = value;
        }
    }
}
class MainClass
{
    static void Main()
    {
        PotionStrength potionStrength = new PotionStrength();
        // SET indexer accessor
        potionStrength[3] = 58.3F;
        potionStrength[5] = 60.1F;
        // GET indexer accessor
        for (int i = 0; i < 10; i++)
        {
            System.Console.WriteLine("Potion #{0} = {1}", i, potionStrength[i]);
        }
    }
}
   /* Output display:
        Potion #0 = 56.2
        Potion #1 = 56.7
        Potion #2 = 56.5
        Potion #3 = 58.3
Press desired key combination and then press ENTER.
C# [] Operator - Arrays and indexers
Square brackets ([]) are used for arrays, indexers, and attributes. They can also be used with pointers.
 Open Source Your Knowledge: become a Contributor and help others learn. Create New Content