Extension methods : Are they better than the real McCoy ?

Posted Sat, May 13 2006 19:54 by bill
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 :)
 
 
 
 
 
Filed under: , , ,

Comments

# Linq up that Webservice

Monday, May 15, 2006 10:31 AM by Nick Randolph's .NET Travels

As with many developers around the globe I downloaded the latest CTP of the Linq technology preview last...

# Linq up that Webservice

Monday, May 15, 2006 8:40 PM by Nick Randolph's .NET Travels

As with many developers around the globe I downloaded the latest CTP of the Linq technology preview last...

# re: Extension methods : Are they better than the real McCoy ?

Thursday, June 29, 2006 8:54 AM by Jim Wooley

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.