Skip to main content

.NET 4.0 Evaluating Properties and Methods at Runtime

One of the enhancement that I really like about .NET 4.0 is the ability to work with DynamicExpression class. Pre .NET 4.0 if you want to pass a List to a function you would have to do something like:

Code Snippet
  1. public static void DoSomethingWithThisList(List<SampleClass> tempList)
  2. {
  3.     //Do something:: With parameter
  4.     foreach(var itemList in tempList)
  5.     {
  6.         var getProperty = itemList.SampleProperty;
  7.     }
  8. }

where SampleClass is an a class or struc (below) containing your properties.

Code Snippet
  1. public class SampleClass
  2. {
  3.     public string SampleProperty { get; set; }
  4. }

Fast forward in .NET 4.0 & 4.5 you could easily pass an anonymous object or list of objects and let the compiler evaluate the methods and properties associated with your custom objects on runtime.
To unleash DynamicExpression:

1- Add reference to "Microsoft.CSharp" or "Microsoft.VisualBasic" to your project
2- Start passing Dynamic objects

Example:
Code Snippet
  1. public static void DoDynamics(List<dynamic> tempList)
  2. {
  3.     //Do something:: with anonymous parameter
  4.     //Intellisense is happy -> Properties are evaluated at runtime
  5.     foreach (var itemList in tempList)
  6.     {
  7.         var getProperty = itemList.SampleProperty;
  8.     }
  9. }

Caveat: I have not tested if there are any performance issues introduced as a result of using DynamicExpressions; however, I would assume that there will be some overhead involved as the compiler have to do some reflection before invoking any custom object methods or calling custom object properties.

Comments