A reader added the following comment to my Neat Tricks With Extension Methods article:
Is it possible to make something like :
Unfortunately, the answer is, no, you can't quite do that. There are two problems here: 1) it's useless to add a generic parameter to a static class because it can never be instantiated (since it's static) and 2) the generic constraint language isn't rich enough to ensure that methods or properties are available on a generic argument unless they already exist in an implemented interface. The solution to the first problem is to make the method generic and not the class. However, the second problem makes this impossible since String and Array don't implement an interface that exposes the Length property. If they did, we could write something like this:
While the reader's request isn't really possible, it did lead me to realize a limitation of the Array.IsNullOrEmpty method that I presented in the previous article. Originally, I had written an extension method called IsNullOrEmpty that worked with arrays. However, it makes sense to broaden the use of this extension method by making it target ICollection like this:
Written that way, our extension method not only works with arrays, but any .NET collection as well!
Happy spelunking!
Page rendered at Tuesday, February 07, 2012 5:54:23 AM (Pacific Standard Time, UTC-08:00)
If feel a bit behind and need to catch up on WPF, this is the book.
Great book on F# containing from Beginner to Advanced. It even has chapters on more arcane features of the language, such as Computation Expressions and Quotations.
Because this book provides source code in Standard ML, it's a fantastic resource for learning F#. One bit of warning: this book does not teach classic data structures. While structures such as binomial heaps and red-black trees are presented, it is assumed that the reader already knows and understands them.
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.