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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top