For my TranslationTester project I need users to be able to specify properties on classes so that they can specify that one property maps to another, and to indicate which property they are mapping (or even excluding).
Up until now I’ve only been able to achieve this using strings that match the property names. This is bad because a) it’s difficult to use, and b) it doesn’t support refactoring very well – (although the tests give helpful exceptions when a property has been renamed it would still need to be manually corrected)
Whilst attending DDD7 I saw a demo on LINQ by Jon Skeet and saw a type of Lambda expression I’d not really seen before that was being used to specify a Key on class. This got me to thinking that this is basically what I want to do. Looking into it I found a few other resources explaining how to do this.
Here’s what I came up with:
which is achieved by:
Note: Some of this is borrowed/inspired very heavily from Moq, particularly the conversion of lambda convert expressions.
One of the nifty things about it is that the syntax of the two Expressions enforces a lot of the requirements on the property types. By using TProp the properties that are referenced in the expressions must be of the same (or common base) type.
I’ve been using the new way of referring to properties and I must say I’m really happy with it!