Return to Snippet

Revision: 17242
at August 28, 2009 03:31 by jimfred


Updated Code
struct Employee
{
    public string name;
    public int age;
    public string location;
};

static void Main(string[] args)
{
    Employee employee;

    employee.name = "Jim Smith";
    employee.age = 35;
    employee.location = "California";

    Type t = employee.GetType();
    System.Reflection.FieldInfo [] fields =
    t.GetFields(System.Reflection.BindingFlags.Instance|System.Reflection.BindingFlags.Public);

    foreach (System.Reflection.FieldInfo field in fields)
    {
        Console.WriteLine(field.Name + " = " + field.GetValue(employee));
    }

    // Expected output:
    //   name = Jim Smith
    //   age = 35
    //   location = California

} // main

Revision: 17241
at August 28, 2009 03:30 by jimfred


Initial Code
struct Employee
{
    public string name;
    public int age;
    public string location;
};

static void Main(string[] args)
{
    Employee employee;

    employee.name = "Jim Smith";
    employee.age = 35;
    employee.location = "California";

    Type t = employee.GetType();
    System.Reflection.FieldInfo [] fields =
    t.GetFields(System.Reflection.BindingFlags.Instance|System.Reflection.BindingFlags.Public);

    foreach (System.Reflection.FieldInfo field in fields)
    {
        Console.WriteLine(field.Name + " = " + field.GetValue(employee));
    }

    // Expected output:
    //   name = Jim Smith
    //   age = 35
    //   location = California

Initial URL
http://www.eggheadcafe.com/conversation.aspx?messageid=29838045&threadid=29837893

Initial Description


Initial Title
Simple enumeration of fields of a struct in C# using reflection

Initial Tags


Initial Language
C#