Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - MyClass.MyProperty[something]

Tags:

c#

I want to do something but not sure how to describe it. I have this class

public class Company {
  private List<Person> _persons;
  private Person GetPersonByName(string name) {
    // My code to select Person is here, which is fine
  }
}

But I want to be able to do this

Company c;
Person p = c.Persons["John"];

which should implicitly call GetPersonByName("John").

Is that possible? What do I need to add to the Company class?

Thanks in advance!

like image 694
Aximili Avatar asked Jun 20 '11 07:06

Aximili


1 Answers

Yes, this is possible. You need to create an accessor class, like the following:

public class Company
{
    private List<Person> _persons;
    public class PersonsIndexer
    {
        Company _owner;
        public PersonsIndexer(Company owner)
        {
            _owner = owner;
        }
        public Person this[string name]
        { 
            get
            {
                 return _owner._persons.FirstOrDefault(x=>x.Name == name); // or whatever code you have there
            }
        }
    }

    public PersonsIndexer Persons{ get; private set; }

    public Company() 
    {
        Persons = new PersonsIndexer(this);
    }

}
like image 169
Zruty Avatar answered Sep 21 '22 02:09

Zruty