0

Possible Duplicate:
Enumerating through an object's properties (string) in C#

Can I use reflection to enumerate all the property name and value of an object?

Community
  • 1
  • 1
user496949
  • 83,087
  • 147
  • 309
  • 426

3 Answers3

3

May be something like below

Say there is a object strList

 PropertyInfo[] info = strList.GetType().GetProperties();

        Dictionary<string, object> propNamesAndValues = new Dictionary<string, object>();

        foreach (PropertyInfo pinfo in info)
        {
            propNamesAndValues.Add(pinfo.Name, pinfo.GetValue(strList, null));
        }              
TalentTuner
  • 17,262
  • 5
  • 38
  • 63
1

try this

var properties = myObj.GetType()
                    .GetProperties(BindingFlags.Instance | BindingFlags.Public);
var propertyNames = properties.Select(p => p.Name);
var propertyValues = properties.Select(p => p.GetValue(myObj, null));
Dean Chalk
  • 20,076
  • 6
  • 59
  • 90
0

Try to use something like this:

MyClass aClass = new MyClass();

Type t = aClass.GetType();
PropertyInfo[] pi = t.GetProperties();

foreach (PropertyInfo prop in pi)
    Console.WriteLine("Prop: {0}", prop.Name);

Hope it will help you.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Dima Shmidt
  • 895
  • 4
  • 13