Reflection is the ability of the .NET framework to gather information (metadata) about assemblies, modules and types at runtime. It allows you also to dynamically create instances of types, invoke methods and access fields, properties and attributes.

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

 

Advertisements