SLoret
SLoret

Reputation: 1541

Is it possible to loop through a C# Class object?

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
}

Upvotes: 8

Views: 3507

Answers (2)

Steve Townsend
Steve Townsend

Reputation: 54138

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

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500055

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

Upvotes: 13

Related Questions