wallah wallah - 7 days ago 5
C# Question

getting value from collection using unknown property name

First, thank you for interest and your help !

swiping out the story, the point is following

I have collection with type Car like below

public class Car {
int a;
int b;

public Car()
{
a = b = 0;
}

public Car(int a, int b)
{
this.a = a;
this.b = b;
}

public int A {
set { a = value; }
get { return a; }
}

public int B {
set { b = value; }
get { return b; }
}
}


ObservableCollection<Car> carColl = new ObservableCollection<Car>();
carColl.Add(new Car(10, 100));
carColl.Add(new Car(20, 200));
carColl.Add(new Car(30, 300));


After several process which I said the story, I got a property name 'A' and 'A' is in a
List<string>
named propertyNames defined as following.

List<string> propertyNames = new List<string>();
propertyNames.Add("A");


Now, I want to do next.

foreach (Car car in carColl)
{
foreach (string propName in propertyNames)
{
// It is what I want to do. But car.propName don't work
Console.WriteLine(car.propName);
}
}


Please, let me know how to that...
thanks a lot

Answer

You have to use reflection:

var properties = TypeDescriptor.GetProperties(typeof(Car));
foreach (Car car in carColl)
{
    foreach (string propName in propertyNames)
    {
        Console.WriteLine(properties[propName].GetValue(car));
    }
}

In case you're new to reflection: With reflection you access meta information of your object (such as exact type, property names, property types) that would otherwise not be available, because it's dropped during compilation. With that meta information you can access your object, e.g. return property values or execute methods.

Comments