Posted By

pauliehaha on 07/29/09


Tagged


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

umang_nine
khouser


Iterate through all properties of a class


 / Published in: C#
 

Reflection is an important capability of the .NET framework and enables you to get information about objects at runtime. In this snippet, we will iterate through all properties for a class named Person using reflection.

The Person class extends System.Object and does not implement any interface. It is a simple class used to store information about a person.

  1. using System;
  2.  
  3. class Program
  4. {
  5. static void Main(string[] args)
  6. {
  7. var person = new Person { Age = 30, Name = "Tony Montana" };
  8. var type = typeof(Person);
  9. var properties = type.GetProperties();
  10.  
  11. foreach (PropertyInfo property in properties)
  12. {
  13. Console.WriteLine("{0} = {1}", property.Name, property.GetValue(person, null));
  14. }
  15.  
  16. Console.Read();
  17. }
  18. }
  19.  
  20. public class Person
  21. {
  22. public int Age { get; set; }
  23. public string Name { get; set; }
  24. }

Report this snippet  

You need to login to post a comment.