Using reflection to access a list of properties that exist in another class

by Edward 22 November 2009 12:20

Ever wondered how to access class properties in another class, that is compiled into another assembly? The only way I figured I could do this, was to use reflection. Reflection provides objects (of type Type) that encapsulate assemblies, modules and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. If you are using attributes in your code, Reflection enables you to access them.

Here is how I did it.

First, remember to reference the reflection namespace in your file.

   1:  using System.Reflection;


You need to add a reference to the assembly, by using the "Add reference", then select the file, from the project you are working from.

You will also have to know the name of the class and first get the type, before you will have to loop through the Type, to access the properties. In my case I know the class I had to access was called "Employee". Once I have this knowledge, all that I still had to do, was find the public properties.

Here is a quick example.

 

   1:   using System.Reflection;
   2:  // ... code here
   3:   
   4:      Type employeeType = typeof(Employee);
   5:      System.Reflection.PropertyInfo[] properties = employeeType.
   6:              GetProperties();
   7:     
   8:   foreach (System.Reflection.PropertyInfo prop in properties) {
   9:          Response.Write(prop.Name);
  10:      }
  11:   
  12:  // ... code here



I hope this will help you, as it helped me.

 

 

Tags: , ,

ASP.NET

Comments are closed

About DasCode.Net

I'm a ASP.NET web developer and code enthusiast. Blogging about everything .Net related.

Code... that's .net

Month List