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 Thursday, November 20, 2008 8:00:29 PM (Eastern Standard Time, UTC-05:00)