csharp

C# Indexer: how to implement the concept of Indexer in c#

Description:

C# Indexer: in this article, I am going to show you how indexer works in c# programming with the help of step by step programming explanation.


C# Indexer

Indexers are a special form of properties that allow an index to be selected To access fields of a class.

Syntax of C# Indexer:

public method_name this [type index]

{

get

{

// Checks index limits and returns the content of the field which

// is identified by the specified index

}

set

{

// assigns the value to the field identified by the c# index

}

}

 

Instead of an identifier, C# Indexer uses the keyword this. This is followed in square brackets Type and identifier of the index variable. The get and set parts of the C# Indexer to generate a bidirectional mapping of the supported C#  index values on the elements.

Almost any data can be used as elements, from simple field values ​​to elements an internal array or a collection, up to calculated values ​​or database fields.



Example: how to implement the concept of C# indexer:

The class shown below defines an indexer that allows access to the elements in the internal values ​​collection as if they were array elements and the objects of the class were the Arrays.

First, make salesdata.txt file in the debug folder in my case the path is C:\Users\Shahzada Fawad\Documents\visual studio 2012\Projects\demo\demo\bin\Debug

Then save some data in this file in my case I save

C# indexer

Then paste the below code

using System;
using System.Collections.Generic;
using System.IO;
public class SalesValues
{
    private List<int> values; // Sales figures in recent years
public SalesValues()
{
values = new List<int>(10);
StreamReader sr = File.OpenText("salesdata.txt");
string line = "";
while (sr.Peek() != -1)
{
line = sr.ReadLine();
values.Add(Convert.ToInt32(line));
}
sr.Close();
}
public double MeanValue
{
get
{
int sum = 0;
foreach (int i in values)
sum += i;
return sum / values.Count;
}
}
public int Size
{
get
{
return values.Count;
}
}
// C# Indexer  that provides access to values in the internal array
public int this[int index]
{
get
    {
        if (index >= 0 && index < 10)
            return values[index];
        else
            throw new IndexOutOfRangeException();
    }
}
}
public class Program
{
    static void Main()
    {
        SalesValues sv = new SalesValues();
        for (int i = 0; i < sv.Size; i++)
            Console.WriteLine(sv[i]);
        Console.WriteLine("\nAverage: {0}", sv.MeanValue);
        Console.ReadKey();
    }
}

output:

C# indexer

 A C# Indexer allows considering an object as an array, each cell providing various object information. The operator [] for accessing an array can then be applied to the object. The index, that is, the value in square brackets, can be of any type and multiple C# Indexers can be specified (for example an index of type int and another of type string, as we will do in the following example). You can also find multiple values ​​(separated by commas) between the square brackets, which allows you to simulate access to arrays of several dimensions.


To implement one or more C# Indexers, you must write one or more functions called this and are written as in the following example (note the square brackets for the arguments to this). We create a Demo class and the square brackets give access to the different wives of XYZ.

The index can be a string. In this case, the C# Indexer returns a number wife or –1 in case of error. To simplify and focus on C# Indexers, no checking array overflow is not performed.

In the Demo class, we keep an array of wife names in private fields. It is created and initialized by the function Weddings. The index on the number is read/write while the index on the name is read-only. To simplify, no verification is carried out on the clues.

using System;

class Demo

{

    string[] Wives;

    public void Weddings(params string[] E)

    {

        Wives = new String[E.Length];

        for (int i = 0; i < E.Length; i++)

            Wives[i] = E[i];

    }

    public string this[int n] // indexer on integer

    {

        get { return Wives[n]; }

        set { Wives[n] = value; }

    }

    public int this[string Name] // C# Indexer  on character string

    {

        get

{

    for (int i = 0; i < Wives.Length; i++)

        if (Wives[i] == Name) return i;

return -1; // no wife of that name

}

    }

}

class Program

{

    static void Main()

    {

        Demo obj = new Demo();

        obj.Weddings("Brigitte", "Catherine", "Jane");

        obj[2] = "Marie-Christine";

        Console.WriteLine(obj[1]); // displays Catherine

        int n = obj["Marie-Christine"]; // n takes the value 2

        Console.ReadKey();

    }

}

Output:

C# indexer

An obj object is an object, constructed like any other object, with new. But roger can be indexed, as if it were an array. When indexed to an integer, obj [i] returns (or modifies) the name of his wife. When it is indexed on a character string, roger [“Brigitte”] returns Brigitte’s serial number in obj list of wives (at different times).


C # allows us to go even further and easily scan obj indexers by writing with an example:

foreach (string s in obj) Console.WriteLine (s);

For this, our Demo class must implement the IEnumerator enumeration with its functions GetEnumerator, MoveNext, Reset, and the Current property:

class Demo: IEnumerator

{

..... // like before

int index = -1;

public IEnumerator GetEnumerator () {index = -1; return this;}

public bool MoveNext () {return ++ index < Wives.Length;}

public void Reset () {index = -1;}

public object Current

{

get {return Wives [index];}

}

}

 

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button