1

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

asked Nov 23, 2016 at 0:12
3
  • The student field isn't assigned until you call the setter, which you aren't doing in Main. Commented Nov 23, 2016 at 0:17
  • you need a list or an array of students Commented Nov 23, 2016 at 0:17
  • @mcNets i am trying to understand the workings of Indexer Commented Nov 23, 2016 at 0:19

1 Answer 1

3

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];
answered Nov 23, 2016 at 0:21
Sign up to request clarification or add additional context in comments.

2 Comments

but when i set s[1]=null, s1 gets an object of Student(). But how is the variable s2 is also getting the value when i have not called a setter on s[2]
@LijinJohn - There is only one backing field, your indexer doesn't use the index parameter at all.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.