8

Is is possible to list our the variable names from the instance and it value.

  public class Car
  {
    public string Color;
    public string Model;
    public string Made;
  }

  protected void Page_Load(object sender, EventArgs e)
  {

//Create new instance
    Car MyCar = new Car();
    MyCar.Color = "Red";
    MyCar.Model = "NISSAN";
    MyCar.Made = "Japan";

//SOMETHING HERE
    foreach (MyCar Variable in MyCar)
    {
      Response.Write("<br/>Variable Name"+  "XXX"+ "Variable Value");
    }

}
1
  • Note that using public fields is usually a bad practice. You should be using properties instead.
    – svick
    May 7, 2011 at 17:00

4 Answers 4

6

Try something like this:

using System;

class Car
{
    public string Color;
    public string Model;
    public string Made;
}

class Example
{
    static void Main()
    {
        var car = new Car
        {
            Color = "Red",
            Model = "NISSAN",
            Made = "Japan"
        };

        foreach (var field in typeof(Car).GetFields())
        {
            Console.WriteLine("{0}: {1}", field.Name, field.GetValue(car));
        }
    }    
}
0
5

You will need Reflection to do it. Here you can see a similar question: How do I get a list of all the public variables I have in a Class? (C#).

Based on it, I think your case will be solved by this code:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    FieldInfo[] myFieldInfo;
    Type myType = typeof(Car);

    myFieldInfo = myType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);

    string result = @"The String fields of Car class are:";

    for (int i = 0; i < myFieldInfo.Length; i++)
    {
        if (myFieldInfo[i].FieldType == typeof(String))
        {
            result += "\r\n" + myFieldInfo[i].Name;
        }
    }

    MessageBox.Show(result);
}

public class Car
{
    public string Color;
    public string Model;
    public string Made;
}
4

This can be done using reflection. But if you want to enumerate whatever is contained within your class, you could simply use a dictionary and enumerate that.

3

Something like this:

foreach (var prop in typeof(Car).GetProperties())
{
  Response.Write(prop.Name + ": " + prop.GetValue(MyCar, null) ?? "(null)");
}
1
  • Then it should be GetFields() instead of GetProperties(), that should work.
    – takrl
    May 7, 2011 at 16:44

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.