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!
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With