Search This Blog

08 November 2010

Using reflection to obtain type information in runtime (C#)

Usually you know which type that you are working with but once in a while you only know what basetype you are working with but doesn't know what subtype you currently have.

During these times reflection is the way to go. Using reflection you are able to find out what type you are working with and create actions based on the fields, events and properties of the type.

I'll start with a short example to show the usage of reflection:

If you send information about events that happens by a webservice and these events are prone to change and it is possible that new events can be added too. If then the webservice usages is so that a presentation of theses events should be created you need to have some way to create a default view of the properties of the different events.

We have three classes defined, one base class and two classes that inherites from this one and defines some properties of themself.

public abstract class MyBaseObject 
   public string Message;
   public string Felmeddelande;

public class MyDateTimeObject : MyBaseObject
   public DateTime StartTime { get; set; }

public class MyOccurenceObject : MyBaseObject
   public int NumberOfTimes{ get; set; }
   public string[] Values { get; set; }
   public string[] Headers { get; set; }

If we now have a method that accepts a parameter of MyBaseObject and want to create functionallity of examining the content of the object we can do as follows:

public class ObjectInspector
   public static InspectObject(MyBaseObject obj)
      var typ = obj.GetType();
      var fields = typ.GetFields();
      var properties = typ.GetProperties();

      foreach(var field in fields)
         Console.WriteLine(string.Format("{0} : {1}", field.Name, field.GetValue(obj));      

      foreach(var prop in properties)
           Console.WriteLine(string.Format("{0} : {1}", prop.Name, prop.GetValue(obj, null));      

A warning, ifyou are to use GetValue of properties then you need to make sure that the method CanRead returns true. This method examines the accessor methods for the different properties and makes sure that the property is readable. Likewise the method CanWrite returns information is the property have a setter.

More information about this can be found in these two articles:

No comments:

Post a Comment