I Dream Of Whidbey: Generics and Anonymous Methods

I Dream Of Whidbey: Generics and Anonymous Methods

We (the team at iP3) are implementing an object model using Whidbey at the moment, and we have been copying and pasting a lot of code lately which is one of the things that I try to minimise as much as possible. One method that we have copied a lot is a simple (and un-optimised) ‘add’ method that helps maintain the many side of a one-to-many relationship.

After creating a method about a week ago that used Generics to allow greater code reuse, I thought that I might be able to use a combination of Generics and Anonymous Methods to allow even more code reuse.

My goal was to create an ‘add’ method that used Generics and Anonymous Methods and could sit in an external class.

The results are below; ClassA and ClassB are the classes that have the relationship, RelationshipHelper is the class with the add method, DelegateTests is the test fixture I created to support me while I refactored the methods for about an hour ;).

I had one stumbling point during this when trying to set the Contains array on ClassA. It would compile just fine, but would fail the test (thank goodness I had a quick and simple test) with a NullReferenceException. It turns out that the anonymous method needed to call a method (yes, even just a private method) to set the _contains member variable. Weird…

It is interesting to note that the standard method size is 266 characters and the much less readable method that used Anonymous Methods and Generics is 227 characters. I think we’ll have to think about whether we want to encourage readability or code reuse with this. I’m leaning towards the standard method because of the readability, but it is great to have implemented this once so we can use it again if a code reuse opportunity arises in the future.