Tue, Oct 9 2007 11:53
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"
Function Cast(Of T)(ByVal obj As Object) As T
Return DirectCast(obj, T)
Function [TryCast](Of T As Class)(ByVal obj As Object) As T
Return TryCast(obj, T)
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)