A few months ago I blogged about using
Extension Methods To Extend The CultureInfo Class. To recap, this is an important technique because it allows you to extend an existing class when (1) you don’t have the original source code and (2) you do not control the code that creates objects of the class you want to extend (and therefore traditional inheritance is useless). What’s new here (to this blog) is that you can do this in the .NET Framework 2.0. This technique has been covered before (in
Daniel Moth’s blog here in May 2007 and later in Adrian Bowles’ MSDN Magazine article "
Basic Instincts - Extension Methods" in November 2007). I’m not going to duplicate that information here and I suggest that you refer to either of these links for the details. To summarise though the basic trick to making this work is that you add back the ExtendedAttribute class to the .NET Framework 2.0 and you’re done. (As the ExtendedAttribute class simply inherits from Attribute and has no other code there’s not much to it).
What I don’t think is so necessarily obvious though is what is meant by adding extension methods to the .NET Framework 2.0. For clarification, whereas the compiled code uses the .NET Framework 2.0 runtime the original source cannot be compiled using the .NET Framework 2.0 compiler; you have to use the .NET Framework 3.5 compiler. The .NET Framework 3.5 compiler is multi-targetting so it can compile code for the .NET Framework 2.0 but only this compiler understands how to interpret the extension method (in C# this means the "this" qualifier in the parameter declaration). So consequently you cannot use Visual Studio 2005 to compile your .NET Framework 2.0 application if you use extension methods; you will have to upgrade to Visual Studio 2008 or else build your app outside of Visual Studio 2005 using the .NET Framework 3.5 compiler.
What also might not be entirely obvious here is the consequence for ASP.NET applications. As ASP.NET website applications are compiled on the fly they use the compiler that is available on the website’s server. For ASP.NET 2.0 applications this will be the .NET Framework 2.0 compiler and the code will not compile.
Technorati Tags:
Extension Methods,
CultureInfo,
Daniel Moth,
Adrian Bowles
Currently rated 3.0 by 5 people
- Currently 3/5 Stars.
- 1
- 2
- 3
- 4
- 5