Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get property name and its value? [duplicate]

Possible Duplicate:
C# How can I get the value of a string property via Reflection?

public class myClass
{
    public int a { get; set; }
    public int b { get; set; }
    public int c { get; set; }
}


public void myMethod(myClass data)
{
    Dictionary<string, string> myDict = new Dictionary<string, string>();
    Type t = data.GetType();
    foreach (PropertyInfo pi in t.GetProperties())
    {
        myDict[pi.Name] = //...value appropiate sended data.
    }
}

Simple class with 3 properties. I send object of this class. How can I i loop get all property names and its values e.g. to one dictionary?

like image 792
Saint Avatar asked Apr 25 '12 11:04

Saint


2 Answers

foreach (PropertyInfo pi in t.GetProperties())
    {
        myDict[pi.Name] = pi.GetValue(data,null)?.ToString();

    }
like image 107
Adrian Iftode Avatar answered Nov 16 '22 16:11

Adrian Iftode


This should do what you need:

MyClass myClass = new MyClass();
Type myClassType = myClass.GetType();
PropertyInfo[] properties = myClassType.GetProperties();

foreach (PropertyInfo property in properties)
{
    Console.WriteLine("Name: " + property.Name + ", Value: " + property.GetValue(myClass, null));
}

Output:

Name: a, Value: 0

Name: b, Value: 0

Name: c, Value: 0

like image 42
James Hill Avatar answered Nov 16 '22 16:11

James Hill