Inline casting

Posted Tue, Oct 9 2007 11:53 by bill

I wrote a couple of really simple extension methods, Cast, and TryCast, that allow me to write code such as sender.Cast(Of Control).Text = "hello world"

   <Extension()> _
   Function Cast(Of T)(ByVal obj As Object) As T
      Return DirectCast(obj, T)
   End Function

   <Extension()> _
   Function [TryCast](Of T As Class)(ByVal obj As Object) As T
      Return TryCast(obj, T)
   End Function

 

Note how the TryCast method requires the AS Class contraint on T. This is because the operation returns a null reference if obj is not of type T. (which you can't do for value types, instead you'd get a default value type, hence the need for the constraint)

Filed under: , ,