c# – Initializing a class with an indexer

Question:

They asked a question during the interview. Is it possible to initialize an instance of a class with an indexer with an initializer block?

class MyClass
{
    private int[] array = new int[5];

    public int this[int index]
    {
        get
        {
            return array[index];
        }
        set
        {
            array[index] = value;
        }
    }
}

class Program
{
    static void Main()
    {
        // Допустима ли чисто теоретически такая инициализация?
        MyClass my = new MyClass(){1,2,3,4,5};

        //my[0] = 1;
        //my[1] = 2;
        //my[2] = 3;
        //my[3] = 4;
        //my[4] = 5;

        Console.ReadKey();
    }
}

If we implement two interfaces iEnumerable and IEnumerator:

class MyClass : IEnumerable, IEnumerator
{
    private int[] array = new int[5];
    int index;

    // Индексатор. 
    public int this[int index]
    {
        get    // Аксессор.
        {
            return array[index];
        }
        set    // Мутатор.
        {
            array[index] = value;
        }
    }

    public IEnumerator GetEnumerator()
    {
        return this;
    }

    public bool MoveNext()
    {
        if(index == array.Length - 1)
        {
            Reset();
            return false;
        }

        index++;
        return true;
    }

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

    public object Current
    {
        get
        {
            return array[index];
        }
    }
}

In the VS initializer block, it swears for each number:

CS1061 'MyClass' does not contain a definition for 'Add' and no extension method 'Add' accepting a first argument of type 'MyClass' could be found (are you missing a using directive or an assembly reference?

How can you implement an Add method in a class for the initializer construct to work? Or is it unacceptable?

Answer:

If you do not need to use the foreach loop , but only need to initialize the values ​​by the initializer block, then you just need to inherit from IEnumerable , in fact, without implementing the GetEnumerator() method itself and add the Add() method:

public class MyClass : IEnumerable
{
    private List<int> array = new List<int>();

    public int this[int index]
    {
        get
        {
            return array[index];
        }
        set
        {
            array[index] = value;
        }
    }

    public IEnumerator GetEnumerator()
    {
        throw new NotImplementedException();
    }

    public void Add(int value)
    {
        this.array.Add(value);
    }
}

Such a class can be initialized as follows:

MyClass instance = new MyClass { 1, 2, 6, 7, 8, 9, 10 }
Scroll to Top