|
A post by Jeremy Miller caught my eye this morning in regards to extension methods in Javascript . While I think that's pretty interesting, I don't think it's a real fair comparison. Instead, I want to revisit C# and even F# with regards to extension methods, because there are a few things I wanted to point out. This is the start of a series covering object oriented programming techniques and how they are used in F#. Note that F# is not only a functional language, but it is a general purpose programming language that supports functional, imperative and object oriented techniques. I hope this series is useful for pointing out that F# fits the need very nicely for object oriented constructs, which is seldom covered. Extension Methods in C# 3.0 With C# 3.0 came the introduction of extension methods which were introduced as part of certain technologies that were LINQ-enabling. Using these, we could add methods, and only public methods, to any given class we choose. So, this gave us the ability to do add methods such as ForIndex to an IEnumerable<T> class such as this: static class Extensions { public static void ForIndex<T>( this IEnumerable<T> items, Action< int , T> action) { var index = 0 ; foreach (var item in items) { action(index, item); index++; } } } var range = Enumerable.Range( 1 , 10 ); range.ForIndex((i, item) => Console.WriteLine( "{0} - {1}" , i, item)); But overall, I thought this was nice, but didn't go quite far enough. Why not extension static methods, properties, events, etc? I'm sure at one point those were considered but somehow dropped along the way, and I think it's a shame quite frankly. Where should it be? If this functionality were to exist in C#, how might it look? Unfortunately, the way it was designed in C# 3.0, it makes it a tad hard to extend for static methods and properties. For example, how might you declare a get or set if what you're declaring is a method such as this? public static bool IsEven( this int value) { get { return value % 2 == 0 ; } } Or if I were to use the property declaration style instead, it seems just as confusing as the above try at this: public static bool this int IsEven { get { return this % 2 == 0 ; } } ...
|