ProgrammerInMaking
ProgrammerInMaking

Reputation: 23

How should I use properties and what should be structure of my class for using indexers across multiple classes

I need help as to how do I go about the structure of classes. How do I use Indexers? I want to have something like

Company.Employees[empId].Employee["Designation"].Salary

To be more specific something like Grid.Rows[rowIndex].Columns["CurrentColumnName"].Width

Upvotes: 1

Views: 98

Answers (3)

Pradeep
Pradeep

Reputation: 26

Actually indexers are used to get element by index, and your EmpId is not a good candidate for indexing as these may be compost or non sequential.

If you still want to use it here is the code. It will mimic as Indexer but its modified version.

class Employee
{
    public int EmpId { get; set; }
    public float Salary { get; set; }
    public string Designation { get; set; }
}

class Employees
{
    List<Employee> EmpList = new List<Employee>();

    public Employee this[int empId]
    {
        get
        {
            return EmpList.Find(x => x.EmpId == empId);
        }
    }
}

Upvotes: 1

Willem Toerien
Willem Toerien

Reputation: 260

I would rather have a method because I can make it generic.

public T GetPropertyValue<T>(string property)
{
    var propertyInfo = GetType().GetProperty(property);
    return (T)propertyInfo.GetValue(this, null);
}

var emp = employee.GetPropertyValue<Employee>("Designation");
var salary = emp.Salary;

That said... Be careful for having so many dot notations. When you get that NullReferenceException on your line in a log file, it is very difficult to find out what exactly was null. So rather break things up a bit and have more lines then you have less trouble of resolving bugs.

Upvotes: 0

bash.d
bash.d

Reputation: 13207

Add a method like

 public string this[string s]
 {
     get{
         if(s == ...)
          return this.property;
     }

 }

Yet, this seems to be more a Situation for Collections, but see here for a complete example.

Upvotes: 2

Related Questions