8

I have a C# class that I want to loop through the properties as a key/value pair but don't know how.

Here is what I would like to do:

Foreach (classobjectproperty prop in classobjectname)
{
    if (prop.name == "somename")
        //do something cool with prop.value
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
SLoret
  • 1,531
  • 3
  • 18
  • 31

2 Answers2

13

Yup:

Type type = typeof(Form); // Or use Type.GetType, etc
foreach (PropertyInfo property in type.GetProperties())
{
    // Do stuff with property
}

This won't give them as key/value pairs, but you can get all kinds of information from a PropertyInfo.

Note that this will only give public properties. For non-public ones, you'd want to use the overload which takes a BindingFlags. If you really want just name/value pairs for instance properties of a particular instance, you could do something like:

var query = foo.GetType()
               .GetProperties(BindingFlags.Public |
                              BindingFlags.Instance)
               // Ignore indexers for simplicity
               .Where(prop => !prop.GetIndexParameters().Any())
               .Select(prop => new { Name = prop.Name,
                                     Value = prop.GetValue(foo, null) });

foreach (var pair in query)
{
    Console.WriteLine("{0} = {1}", pair.Name, pair.Value);
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

Check out the solutions here - although that restricts to public properies the approach should work for you to get them all.

Community
  • 1
  • 1
Steve Townsend
  • 53,498
  • 9
  • 91
  • 140