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 :)