Property with indexers

  • Thread starter Thread starter Alberto
  • Start date Start date
A

Alberto

I have a class and I want to create a property but I need it work as an
indexer. For example:

pupil.calification[3] = 8;

Can you tell me how to do it?
Thank you very much.
 
You want syntax like this in your pupil class...
int this[int index]
{
set
{
// use index and value to set your data
}
}
 
Hi Alberto,

Alberto said:
I have a class and I want to create a property but I need it work as an
indexer. For example:

pupil.calification[3] = 8;

Can you tell me how to do it?
Thank you very much.

The calification property will need to return an object that defines an
indexer (indexers can only be defined for classes, not properties, methods,
etc.).

Regards,
Daniel
 
A full example might be:

public class Pupil {
public int this[int index] {
get { }
set { }
}
}

In the above case you can do:

Pupil p = new Pupil();
p[3] = 8;

However, that isn't what you want. You need it on the property.

public class Calification {
public int this[int index] {
get { } // Implement these
set { } // Implement these
}
}

public class Pupil {
private Calification calification = new Calification();
public Calification Calification {
get { return this.calification; }
}
}

Now you can call:

Pupil p = new Pupil();
p.Calification[3] = 8;

The Calification class is going to be holding your data in this instance. You
may
want to nest this class within your Pupil class such that it behaves more like a
member and you can enforce data protection.
 
Back
Top