Lijin John Lijin John - 17 days ago 7
C# Question

Why my Indexer is not working?


Indexers allow instances of a class or struct to be indexed just like
arrays. Indexers resemble properties except that their accessors take
parameters.


I have a code like this

class StudentMemento
{
Student student;
public Student this[int index]
{
get { return student; }
set { student = new Student { time = DateTime.Now }; }
}
}
class Client
{
static void Main()
{
StudentMemento s = new StudentMemento();
Student s1 = s[1];
Student s2 = s[2];
Student s3 = s[1];
Console.Read();
}
}


According to the documentation in msdn i should get an instance of Student in the following members s1,s2 because i am returning an object of Student int the Indexer but i am getting a null reference. Can anyone help me understand, why is that so. Thanks

Lee Lee
Answer

After

StudentMemento s = new StudentMemento();

s.student will be null. The student field is only assigned within the indexer setter, so you need to call that before calling the getter e.g.

StudentMemento s = new StudentMemento();
s[1] = null;

Student s1 = s[1];
Student s2 = s[2];
Student s3 = s[1];