Tag Archives: Reflection

Get Value of Unknown Type From Unknown Object

In a previous post I mentioned a content management system I built for dynamically creating email content to notify users of events.  The system is delivered via a RESTful web service that is called from disparate websites and programs within our software ecosystem.  The basic requirement of the content builder is that those calling systems only need to provide a few key values.  From that information it can determine what database object to gather data from and what content templates to use for building the email notifications.

The design of the system rests on the Abstract Factory design pattern.  This allows the system to determine at run time what objects to create.  In doing this the system uses reflection in a number of ways, one I discussed in a previous post mentioned above.  Another I’m going to share in this post.

The system is passed an object which contains all the possible key fields needed to determine what data and content are needed.  Depending on which key fields are populated, the system will create the needed data objects and apply the correct rules and templates for constructing the template.

Example Class:

namespace Extensions
    public static class ObjectExtensions
       public static T GetPropertyValue<T>(this object sourceObject, string key)
         if (sourceObject.GetType().GetProperty(key) == null)
            return default(T);
         return (T)sourceObject.GetType().GetProperty(key).GetValue(sourceObject, null);


The class is static because I like to write these sort of methods as extensions.  I find them easier to use as a developer and really we just want to extend this method to any object.   The method returns the generic type T because we don’t know what type the property we’re looking up is until run time.

The method first checks to see if the property(key) being requested exists.  If  it does not we return the default value of the generic type.  In my system this works fine.  Returning a null for a string or a zero for an integer will net the same affect because it’s as good as it not being populated.  In other implementation you may want to throw an error here.

If the property exists then the value is returned to the caller it’s all done.  You might ask, what if the property they pass as the “key” does not have a type of “T”?  I contemplated that, one option could be to just return the default of the type T in that scenario.  Instead, I decided not to handle that and allow the .Net framework to bubble the error up to the caller and allow it to make a decision on what to do.  I’m not a big fan of validating methods are being called correctly in my logic layer or adding too much error handling.  If not done correctly errors can be masked from the calling program and hidden. Below are a few unit tests that show how the method works.

Unit Tests:

public class ObjectExtensionsTests
   public class SourceObject
      public int Id { get; set; }
      public string Ids { get; set; }

   public void ValueExistsAndIsReturned()
      var s = new SourceObject {Id = 123456};
      Assert.AreEqual(123456, s.GetPropertyValue<int>( "Id"));

  public void ValueDoesNotExistsAndDefaultIntValueIsReturned()
     var s = new SourceObject { Id = 123456 };
     Assert.AreEqual(0, s.GetPropertyValue<int>("Id2"));


  public void ValueDoesNotExistsAndDefaultStringValueIsReturned()
     var s = new SourceObject { Ids = "123456" };
     Assert.AreEqual(null, s.GetPropertyValue<string>("Id2"));


  public void WrongTypeErrorReturned()
    var error = false;
      var s = new SourceObject { Id = 123456 };
      Assert.AreEqual(null, s.GetPropertyValue<string>("Id"));
    catch (Exception)
       error = true;

    Assert.AreEqual(true, error);


There you have it. A simple extension method to get the value of an unknown property on an unknown object.

Object Reflection In JavaScript

Reflection is a powerful technique that I’ve used a lot in C#. On several occasions I’ve found some uses for this technique in JavaScript too. Most recently, I was writing a test harness for a RESTFul web service to allow our QA folks a easy way to test it. Typically, when I’m writing these kinds of things I have a couple objectives in mind.

First, I don’t want to turn the testing tool into a maintenance item. That is, if there are updates to the software being tested (a web service in this case) I don’t want to have to update the tool.

Second, I don’t want to add another uncontrolled variable to the testing.   Meaning, I don’t want the testing tool to require extensive QA or to create a layer of possible bugs to be validated anytime QA finds an issue with the software being tested.

Finally, I don’t want to spend a lot of time on it and I’d like to reuse it. It’s an internal tool that is usually being used by a semi-technical person and has a very specific purpose, being pretty isn’t one of them. And, if I can use it again, for another web service in this case, double bonus!

In the case of the RESTFul Web Service testing tool I accomplished this in two ways.

First, I build the inputs for the service by parsing the web service schema (.xsd) dynamical. This way, if new inputs are added I don’t have to update the testing tool. I probably write a post on that part another day.

Second, I output the results (which are returned in JSON) to a web page using reflection after the JSON object is parsed to a JavaScript object.

Here is an example of how I do it:

Consider the following object. It has a set of properties, a nested object, and a function.

var obj = new Object;
obj.FirstName = “John”;
obj.LastName = “Smith”;
obj.FullName = “John Smith”;
obj.Address = “Main Street”;
obj.Phone = “999-999-9999”
obj.GetName = (function () {});
obj.History = new Object();
obj.History.PreviousAddress = “South Street”;
obj.History.PreviousPhone = “888-888-8888”;

All I want to do is print each property and it’s value to the screen. And, if there is a nested object I want to print it’s properties too. This will allow the return results to be validated.

To do this I use a script like this:

function DisplayObjectProperties(obj) {
for (prop in obj) {
var text = “”
if(typeof obj[prop] != “function” && typeof obj[prop] != “object”){
text = prop + “: ” + obj[prop];
else if (typeof obj[prop] === “object”) {
$(“body”).append(“<div>”+ text + “</div>”);

Nothing too much going on here, just a loop through the object and appending each property name and it’s value to an html element.  The important thing is to test the type, so you can handle nested objects, arrays, functions, etc however you might want to.  In my case, if there is a nested object I want to display it’s properties too.  I do that with a recursive call to the function passing the nested object.

Call it:  Just pass the object to the function it will do the rest.



FirstName: John
LastName: Smith
FullName: John Smith
Address: Main Street
Phone: 999-999-9999
PreviousAddress: South Street
PreviousPhone: 888-888-8888

Invoke base class methods on unknown types

I recently built a system that dynamically builds content for sending messages to users after certain events.  As is with most of these types of systems the content is mostly static and stored in a repository with “holder values” that are replaced at run time from a data source.  The architecture of this system is one that is very configurable.  Meaning, a new message can be created using configuration files no additional coding necessary.  One of the challenges this presented was how to handle formatting of data types that are not known until run time.

Use Case:

The content may look something like: “Your bill with a billing date of _date for _amount is overdue.”  The holder values are _date and _amount; the data source might store the amount as a number and the date including the time (100 & 12/31/2012 08:35:55).  However, this data would need to be formatted as $100.00 and 12/31/2012 for a user facing message.

The system needed to handle any possible formatting of data without knowing at build time what they might be.  To accomplish that I store a pointer to a data source for each “holder value”, which includes a mapping to a base class method (and the required parameters) of the underlying data type.  Then, when replacing holder values with the  real values from the data source I apply the method using reflection.

Here’s some sample code and a quick explanation:

public static string InvokeSomeMethod(string method, string parameters, string value)

            Object v = ConvertValue(value);
            var pList = ParseMethodParameters(parameters);
            var rt = v.GetType().GetMethod(method, GetParameterTypes(pList)).ReturnType.FullName;
            return InvokeMethod(v, rt, method, pList);

“Let me explain. No, there is too much. Let me sum up”:

We can’t just invoke a method all willy nilly like, first we need to know a few more things.

  • What type are we dealing with?
  • What is the return type of the method? (Beware of overloads)

A little more detail:


The values I’m dealing with are strings, however, I may need to execute a method on it’s “true” type.  In order to get the type I call ConvertValue (line 1 above) which passes the value through a series of tests to determine what type it is and convert it.  I won’t bore you with the entire method, but this should give you an idea what I mean.

 public static object ConvertValue(string value)
            if (ParameterIsInt(value))
                return Convert.ToInt32(value);
            if (ParameterIsDouble(value))
                return Convert.ToDouble(value);
              if (ParameterIsDate(value))
                 return Convert.ToDateTime(value);

Each sub-function does something like this:

 public static bool ParameterIsDate( string value)
            DateTime d;
             bool result = DateTime.TryParse(value,  out d);
             if (result)
                 return true;
                 return false;

Return Type and the Parameter List:

Remember above where I said beware of overloads when getting the return type.  The parameter list has to be parsed and passed when getting the method return type in order to get the correct method. When I parse the list I reuse the convert value function to get the correct type of the parameter, this is key to the getting the method.  And of course the parsed parameters are passed when invoking the method.


So far this method (as part of a larger highly flexible system) has worked very well and allowed us to create a lot of new content with little to no new lines of code.  One down side, the person building the configurations has to  know the base class methods and parameters (absent a user interface for the content management) to format the data.  Another issue was the convert value function.  When I originally built the system I just added the half dozen or so common data types.  However, if a new one comes up some coding will have to be added.  I do have a possible solution to that issue.  In some other similar systems I’ve used Convert.Change Type to change strings to the “real type”.  This works well as long as you know what type you want.  If not, your still forced to call the various try parse methods to get the type.  In a system like the one were using, we could leverage the configuration to pass a type to the Convert.ChangeType method and get rid of the try parse convert to methods.  I’ll probably add that the first time I have a new data type come up, so far it hasn’t.

%d bloggers like this: