I've been toying with Orcas extension methods recently, and I came across a situation that could be problematic. The problem involves value types. Generally, the advice to people is to always make value types immutable. That is, once a type is constructed, it's state cannot be changed. There are a number of reasons behind this, and now there's one more.
Extension methods allow you to make a static method look like an instance method on another class via the "this" keyword on the first parameter. The compiler will then use that method if it is in scope when resolving methods in code. So, the first parameter to the method behaves roughly like the "this" pointer. However, there is a subtle difference when extending value types in this way.
In a regular instance method, the "this" parameter is passed by reference, even for a value type. (In IL, you load an address onto the stack rather than the instance) This allows you to change the state of the object within the method. However, for extension methods, the first parameter is passed by value.
So, if you attempt to make changes to the state of a value type in an extension method on that type, the changes won't be reflected after the method completes.
Like most value type problems, this is because you've made changes to a copy of your instance rather than the "original". So, keep you value types immutable, or be aware of all the various gotchas of mutable value types.
Remember Me
Page rendered at Monday, September 08, 2008 7:24:22 AM (Pacific Standard Time, UTC-08:00)
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.