Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to list our all the string variable names and values out

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");
    }

}
like image 370
SMTPGUY01 Avatar asked May 07 '11 16:05

SMTPGUY01


Video Answer


1 Answers

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));
        }
    }    
}
like image 53
Andrew Hare Avatar answered Sep 21 '22 20:09

Andrew Hare