Use of indexers on properties in a customer class

Been google.ing for some time now and nothing seems to match my specific issue.

I have created my own class with some properties such as

public class cPerson
{
  public int? iID {get;set;}
  public string sName { get; set; }
  public bool? bGoodGuy { get; set; }
}

then i create an instance of this class

cPerson myPerson = new cPerson()

and add values

myPerson.iID=10;
myPerson.sName="John Smith";
myPerson.bGoodGuy=true;

and then if i want to display this person i would do

writeline("Persons id : " + myPerson.iID);
writeLine("Persons name : " + myPerson.sName);
writeLine("Person is good : " + myPerson.bGoodGuy);

But what i would like is to write it out based on what order the property is defined in my class so

writeline("Persons id : " + myPerson[0]);
writeLine("Persons name : " + myPerson[1]);
writeLine("Person is good : " + myPerson[2]);

And this is not working.

I just assume that this is doable with an indexer of some sort, however the samples i have found is for indexing several persons, such as:

writeLine("Person 0's id is : " + myPerson[0].iID);
writeLine("Person 0's name is : " + myPerson[0].sName);
writeLine("Person 0's good or bad status is : " + myPerson[0].bGoodGuy);

But that is NOT what im after.

Some one (C#) sharp enough to give me some direction i would very much appreciate it.

Regards

A Swede

Jon Skeet
people
quotationmark

Firstly, this seems like a generally bad idea. If you find yourself really needing this, you should carefully consider design alternatives.

Secondly, it's not clear that you can get the properties in declaration order - I would strongly consider a more clear-cut ordering, such as alphabetical.

If you really want to do this, you can add an indexer like this:

public object this[int index]
{
    get
    {
        // Alternative: remove the hard-coding, and fetch the properties
        // via reflection.
        switch(index)
        {
            // Note: property names changed to conform to .NET conventions
            case 0: return Id;
            case 1: return Name;
            case 2: return GoodGuy;
            default: throw new ArgumentOutOfRangeException("index");
        }
    }
}

... but as I say, I wouldn't do this.

An alternative would be to have a Properties property or method which created an IEnumerable<object>, possibly via reflection. For example:

public IEnumerable<object> Properties()
{
    return typeof(Person).GetProperties()
                         .OrderBy(p => p.Name)
                         .Select(p => p.GetValue(this, null));
}

You could then use:

Console.WriteLine("Persons id : " + myPerson.Properties().ElementAt(0));

Further, if you really wanted to, you could make this an extension method on any object. Again, I'd be wary of doing any of this though.

people

See more on this question at Stackoverflow