Accessing all the properties of an instance using reflection

In this article I explains about how to Accessing all the properties of an instance using reflection.

Here's a simple example of Reflection which is used to read the all properties from an instance. PropertyInfo class is used to access the specific property of the instance, using this we can get or set the value for the instance. It is very use full when you don’t know the type of the instance.

public class Student
private string m_Name;
public string Name
get { return m_Name; }
set { m_Name = value; }

private int m_Id;
public int Id
get { return m_Id; }
set { m_Id = value; }

private int m_Age;
public int Age
get { return m_Age; }
set { m_Age = value; }

The bellow code is used to access the properties of the Studnet class

public partial class Form1 : Form
public Form1()

private void Form1_Load(object sender, EventArgs e)
Student obj = new Student();
obj.Name = "Jax";
obj.Id = 1298;
obj.Age = 23;

public void ReadAllTheProperties(object obj)
//Getting all the properties into an array
PropertyInfo[] propInfo = obj.GetType().GetProperties();

//Looping the array
foreach (PropertyInfo pi in propInfo)
string value = string.Empty;
string name = string.Empty;
name = pi.Name;
value = pi.GetValue(obj, null).ToString();
MessageBox.Show(name + "=" + value);



Author: gopal30 Nov 2009 Member Level: Bronze   Points : 0

Thnx For the code..Its useful for me..

Author: macxima16 Feb 2010 Member Level: Gold   Points : 1

Thanks for explaination of reflection. This is a simple example to explain accessing property by refelection

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: