Mr Billy
Mr Billy

Reputation: 151

Implementing indexing in C# property

For what i have been reading, with another Class I would be able to add the indexing to the property. But i am not managing to achieve the get/set of the "Option[x]" property of my custom "Poll" class.

public class Poll
{
    //Constructor
    public Poll() { }
    //Properties
    public string Title
    {
        get { return title; }
        set { title = value; }
    }
    public Options Option { get; set; }
    private string title;
}
public class Options
{
    string[] option = { };
    public string this[int i]
    {
        get { return option[i]; }
        set { option[i] = value; }
    }
}

When i try to add the first option to the poll, it says the object ("Options") has not being instantiated. And it does make sense. But I couldn't figure out where in Poll i would instantiate it.

So, can anyone explain me what am i doing wrong? Am i following the right direction? Or point to me further reading. For the solutions I have seen, this one seemed the most logical to me, but was only a small raw example, low on details.

I didn't want to follow the dictionary (Implementing indexing "operator" in on a class in C#) way, or "Option" property returning a List of strings.

Upvotes: 2

Views: 127

Answers (1)

user
user

Reputation: 62

Change:

public Poll() { }

To:

public Poll() { Option = new Options(); }

Also pay attention to "Wai Ha Lee" pointed out: "the indexer will always throw an IndexOutOfRangeException because the option array is always an empty array."

What he means is that you have to replace:

string[] option = { };

With:

string[] option = new string[X]; //X is Array size

Upvotes: 1

Related Questions