Tuesday, January 06, 2009
Dynamic Property and Method Access
The upcoming version of Milos has a nifty little enhancement in the ObjectHelper class: It makes it easier to dynamically access/set properties and invoke methods. This is useful in scenarios that can otherwise only be handled with Reflection.
Example: Consider a scenario where a customer object is provided by some external system (perhaps from a dynamic language) and you need to access or set a name property. This can now be done like so in Milos:
object customer = GetCustomerObjectFromSomewhere();
string firstName = EPS.Utilities.ObjectHelper.GetPropertyValue<string>(customer, "FirstName");
EPS.Utilities.ObjectHelper.SetPropertyValue(customer, "LastName", "Smith");
Note that these methods are also available as extension methods. To use the extension methods, the EPS.Utilities namespace has to be included at a file level, by putting the following using statement at the top of your source file:
using EPS.Utilities;
Now, the above code can be simplified to the following:
object customer = GetCustomerObjectFromSomewhere();
string firstName = customer.GetPropertyValue<string>("FirstName");
customer.SetPropertyValue("LastName", "Smith");
Milos now also makes it easier to invoke methods dynamically. For instance, one can call a method ont he same object like so:
string name = customer.InvokeMethod<string>("GetFullName", null);
Note that the second parameter is an array of parameters that get passed to the method. For instance, if the GetFullName() method takes an integer and a string parameter, it could be passed like so:
object[] parameters = { 0, "Test" };
string name = customer.InvokeMethod<string>("GetFullName", parameters);
Note that C# 4.0 (once released) will provide features to also make it easier to do these things. In C# 4.0, the following syntax would be valid:
dynamic customer = GetCustomerObjectFromSomewhere();
string firstName = customer.FirstName;
customer.LastName = "Smith";
string name = customer.GetFullName(1, "Test");
The example used here, with the Customer object dynamically retrieved somewhere is one scenario where this is useful. There are other scenarios as well, where generic code is written that can operate on types that are defined elsewhere. Data binding scenarios are one example.
Posted @ 9:47 AM by Egger, Markus (markus@code-magazine.com) -
Comments (77)