Friday, September 21, 2012

.NET 4 dynamic feature

When .NET 4 was coming out a couple of years ago, one of the neat new features was the inclusion of (better support for?) dynamic languages. C# even got some love and the dynamic keyword was added. I was quite excited about the prospect of having dynamic coding features in my C# code base. Now about 3 years later I have finally used the dynamic keyword; once in "real" code and once for debugging purposes.
 
Now that I have used the feature, it has opened my eyes to other opportunities to leverage it. I hope this helps someone else too.

The first time I used the dynamic keyword was when I needed to access some COM interop component. My specific example is when I wanted access to the document of a WPF WebBroswer object. The problem is the WebBrowser.Document property is of type System.Object. As I debug, I can peek into the object and see that it has the title property I want with all the data I need. However, you need to cast it to the COM object to use it in code. I have always been a bit queasy when I need to do COM interop.

Regardless of my feelings towards COM interop, there could be COM interface version issues depending on the version of Browser installed and it just seems like a big hammer for simply getting the title from the Document property. Well this clever clogs had already posted a super simple solution to my problem; just use the dynamic keyword. I know I want the title property, I just don't care which interface is used to get it. Great stuff!

Today I find myself hacking around a part of a code base that I am unfamiliar with. There seems to be some sort of On^2 operation introduced into the code base. I want to hack in some logging into a Generic usercontrol that is doing too much work. When I go to log the events I just get the Infragistics* DataRecord's ToString() implementation filling up my logs. I know that in this case I have a Deal in the data context for the problem I am logging, but it is an open generic type of T in the control. The control has no reference to the assembly that the Deal object lives but I want to log the Deal.DealId property. I want to see the DealId so I know if we are looping over the same deal the whole time or if we have jitter or just double handling etc...

Well you guessed it, where I need to get the DealId, I just assign the DataRecord's DataItem to a dynamic variable and then just log the magical DealId property on that dynamic object. Super! (Obviously once we found the issue, I ripped out my hack)
 
So I don’t think this is a feature I will use a lot of, but it really helped in these two scenarios.