Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 105
  • Last Modified:

Collection C#

trying to understand when I do call public Person this[int index] {get {
                return (Person)List[index];
  I'm just a little new trying to understand this concept..

class PersonCollection : CollectionBase
    {
        public void Add(Person person) {
            List.Add(person);

            }

        public void Insert(int index, Person person) {
            List.Insert(index, person);
        
        }

        public void Remove(Person person) {
            List.Remove(person);
            }

        public Person this[int index] {

            get {
                return (Person)List[index];
            
            }
            set
            {
                List[index] = value;
            
                }
        
            }    
    }

Open in new window


PersonCollection person = new PersonCollection();
            person.Add(new Person() {
            PersonID = 1,
            Name = "Yves",
            LName ="Guyon"
            
                });

            person.Add(new Person()
            {
                PersonID = 2,
                Name = "Steve",
                LName = "Smith"

            });

            person.Add(new Person()
            {
                PersonID = 3,
                Name = "Mark",
                LName = "Guyon"

            });

            person.Add(new Person()
            {
                PersonID = 3,
                Name = "Mark",
                LName = "Guyon"

            });

Open in new window

0
yguyon28
Asked:
yguyon28
1 Solution
 
käµfm³d 👽Commented:
Assuming I understand what you are asking, you would access the indexer in this manner:

PersonCollection person = new PersonCollection();

...

Person p = person[0];

Open in new window


You can do this because you defined your indexer to accept integers as parameters.
0
 
Jaime OlivaresCommented:
the this[ ] construction converts your class into an indexable one.
It is expected that you reference an internal collection inside that class, in order to get the real data and return it in the 'get' block.
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now