Reflection is an important capability of the .NET framework and enables you to get information about objects at runtime. In this article, we will iterate through all properties for a class named Person using reflection.
using System;
using System.Reflection;
class Program
{
static void Main(string[] args)
{
Person person = new Person();
person.Age = 27;
person.Name = "Fernando Vezzali";
Type type = typeof(Person);
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
Console.WriteLine("{0} = {1}", property.Name, property.GetValue(person, null));
}
Console.Read();
}
}
The Person class extends System.Object and does not implement any interface. It is a simple class used to store information about a person:
class Person
{
private int age;
private string name;
public int Age
{
get { return age; }
set { age = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
}
The ASP.NET Wiki was started by Scott Hanselman in February of 2008. The idea is that folks spend a lot of time trolling the blogs, googlinglive-searching for answers to common "How To" questions. There's piles of fantastic community-created and MSFT-created content out there, but if it's not found by a search engine and the right combination of keywords, it's often lost.
The ASP.NET Wiki articles moved to CodeProject in October 2013 and will live on, loved, protected and updated by the community.