No, you would need to use the property name:
string fname = people[0].FirstName;
The syntax you're suggesting would only work if your class had an indexer:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string this[int index]
{
get
{
switch (index)
{
case 0: return FirstName;
case 1: return LastName;
default: throw new IndexOutOfRangeException();
}
}
}
}
...
string fname = people[0][0];
Indexers - C# Programming Guide | Microsoft Docs[
^]
If you want to iterate over all of the properties in your class, you'd have to use Reflection or the
TypeDescriptor
.
Reflection (C#) | Microsoft Docs[
^]
TypeDescriptor Class (System.ComponentModel) | Microsoft Docs[
^]
For example:
using System.Collections.Generic;
using System.ComponentModel;
...
public static void DumpList<T>(IEnumerable<T> list)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
foreach (T item in list)
{
Console.WriteLine("{");
foreach (PropertyDescriptor property in properties)
{
Console.WriteLine(" {0} = {1}", property.Name, property.GetValue(item));
}
Console.WriteLine("}");
}
}
Usage:
List<Person> people = new List<Person>
{
new Person { FirstName = "Mark", LastName = "Miller" },
new Person { FirstName = "Nancy", LastName = "Miller" }
};
DumpList(people);