Friday, November 06, 2009

Extensions methods FTW

Extension methods is my favorite language feature of .Net. Although they are just symantic sugar they provide a nice way of compacting code to express its real intent.

Here is a collection of my favourite homemade extension methods. Most have been included in the plain framework.

#1: My extension method for making !string.IsNullOrEmpty(somestring) more readable.

#2: Bringing the IN operator from sql to .net. It's implemented on enums but could be any type.

#3: Execute an operation on a collection. I use this all the time and I also have a version that can return the result of an operation as a new collection. That is basically equal to what the .Select extension from System.Linq does. The functional approach of F# inspired me to this.

#4: Get a typesafe value from a web request

#5: Gets all the controls of a certain type from a form. Originally I also had a version that operated on any type of object. I soon found out that searching an object structure without any constraints is a performance disaster. Being limited to finding controls on a form is much better as it's a well defined hierarchy that easy and fast to traverse. The idea springs from looking at JQuery. Some examples of usage can be found in my blogspot about oneliners in .net

#6 Save an object. This operates on types not defined yet. If you implement the IBusinessEntity<> interface you will automatically get a Save() method. It gives a feeling and ease of use as that of the Active Record pattern, without the object knowing anything about persistence. The plain framework also contains extension methods for Delete() and Validate().

What would make this perfect is the ability to define extension methods to be used in a static context. If my business class was Product, I would then be able have a Product.Get(...) method. That would be cool.

No comments:

Post a Comment