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.

6
  • 1
    You want reflection or a dictionary. Commented Jun 28, 2013 at 18:01
  • 1
    Just to clarify anyone else (it took me a min to figure out) I think he is asking about using reflection to search for the property selected in MyVariable and add that to the list box. Commented Jun 28, 2013 at 18:02
  • 1
    Are you using Winforms or WPF? Binding is the solution to this, but it is different depending on which you are using. Commented Jun 28, 2013 at 18:02
  • What are you trying to do? you Could do Color MyColor = Car.Color; maybe if thats your goal. Commented Jun 28, 2013 at 18:04
  • possible duplicate of Get property value by string Commented Jun 28, 2013 at 18:05

1 Answer 1

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.)

Sign up to request clarification or add additional context in comments.

7 Comments

@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.
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 : 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, your code shows: "No overload for GetValue method..." I don't know what is "binking instead". I will seek more information.
yeah this seems like using symbolic references in Perl... tread carefully.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.