Extension methods : Are they better than the real McCoy ?

I was just reading Avner’s blog entry about the latest LINQ bits and VB 9.0, in particular the bit about the Value Extension Property.  How cool is that !!!! 🙂
 
So it occurred to me that perhaps extension properties are better than “normal” properties.  Because an extension property is basically a shared property that get’s passed an instance of the type being extended, it allows the testing for null to be encapsulated in the property itself..  This allows you to write cascading statements without needing to break them into temporary variables and null tests, eg:
 
consider this code using normal properties:
  Dim doc as Documents = MyDocs.ActiveDocument
  Dim hdr as Header
  If doc IsNot Nothing Then
     hdr = doc.Header
  End If
  Dim style As Style
  If hdr IsNot Nothing Then 
    style = hdr.Style
  End If
 
Now look at it if all those properties were extension methods :
 
Dim style As Style = MyDocs.ActiveDocument.Header.Style
 
Because extension methods allow null propagation, we don’t need to test for null along the way.  that is, rather than focusing on the wiring, we can instead focus on the task 🙂
 
 
 
 
 


1 Comment so far

  1.   Jim Wooley on June 29th, 2006          

    I’m concerned that Extension Properties (members) may well give us a slippery slope leading to a breakdown of encapsulation. We have seen how multiple inheritance is a dangerous thing. Extension methods are powerful (see http://devauthority.com/blogs/jwooley/archive/2006/05/21/1095.aspx), but a gun waiting to be fired (see http://devauthority.com/blogs/jwooley/archive/2006/05/02/935.aspx). Extension properties may be the bomb that breaks OOP.