1
public class Car
 {
     public string Color { get; set; }
     public string Model { get; set; }
 }

How I call "Car.Color" or "Car.Model" from a variable?

Ex.

string MyVariable = "Color";
MyListBox.Items.Add(Car.Model); //It Works Ok
MyListBox.Items.Add(Car.MyVariable); // How??

Regards.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
karmany  
  • 39
  • 1
  • 6

1 Answers1

11

You'd have to use reflection. For example:

var property = typeof(Car).GetProperty(MyVariable);
MyListBox.Items.Add(property.GetValue(Car)); // .NET 4.5

Or:

var property = typeof(Car).GetProperty(MyVariable);
MyListBox.Items.Add(property.GetValue(Car, null)); // Prior to .NET 4.5

(Your sample code would be clearer if you used a different name for the variable Car than the type Car, mind you. Ditto MyVariable which doesn't look like a variable in normal .NET naming conventions.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • @karmany: It's worth noting that this is the sort of thing you don't want to be doing most of the time. We don't really have enough context to know whether it's the most appropriate approach *here*, or whether binding would be better as Scott suggested. – Jon Skeet Jun 28 '13 at 18:04
  • Car is a query's result (LINQ to Dataset). When a user selects "Color" Field (in the query), I want to fill a list (MyListBox) only with the "Color" Field. – karmany   Jun 28 '13 at 18:16
  • 2
    @karmany : Then that sounds like you *should* be using binding instead. Set the display property based on the query, but actually populate the listbox with the full `Car` references. – Jon Skeet Jun 28 '13 at 18:17
  • Jon, your code shows: "No overload for GetValue method..." I don't know what is "binking instead". I will seek more information. – karmany   Jun 28 '13 at 18:31
  • yeah this seems like using symbolic references in Perl... tread carefully. – gudatcomputers Jun 28 '13 at 18:33
  • This code works fine: var property = typeof(Car).GetProperty(MyVariable); MyListBox.Items.Add(property.GetValue(Car,null)); if you could edit your answer. Very thanks!! – karmany   Jun 28 '13 at 19:04
  • @karmany : My code should work fine in .NET 4.5; the overload was added then. I'll edit the answer to make that clear. – Jon Skeet Jun 28 '13 at 20:25