late bound conversions with generics !

Posted Thu, Aug 4 2005 20:08 by bill

 

I got  a note in my inbox today from Cameron Beccario, letting me know his blog has moved (new rss here).  Cameron has been busy in Japan (hopefully NOT pigging out on whale meat), having managed to learn Japanese, he's now working there.  Anyway, Cameron said I might be interested in his latest blog entry, and he was right :)

 

Cameron does touch on a couple of "interesting" issues, such as conversions with generic types.  Cameron's  approach works well in the second scenario he shows, one where you don't necessarily have full control of the code. (I'm assuming that the AddRow method has to convert the string to a DelimetedPair(Of L, R)).

But where I would argue against this, is in the output.  It is FAR FAR preferable to call ToString rather than try a conversion. The basic reason is, that op_Implicit (Widening) and op_Explicit (Narrowing) conversions, are all Shared (aka static for those that are semi-colon retentive).  And Shared methods should generally not be used where the type in question is not sealed (not marked as NotInheritable or not Structure) .  There are exceptions to that, sure, but I still think that using interfaces is preferable, and ideally you should use instance methods.  So where Cameron had :

 

   Shared Narrowing Operator CType(ByVal Value As DelimitedPair(Of L, R)) As String
        'TODO: Error checking.
        Return _
            LateCType(Of String)(Value.m_Left) & _
            Delimiter & _
            LateCType(Of String)(Value.m_Right)
    End Operator

    Public Overrides Function ToString() As String
        Return CStr(Me)
    End Function

 

That actually should have been the other way round.  That is, the CType operator method should have called the instance method, not the instance method calling a shared method.

  Shared Narrowing Operator CType(ByVal Value As DelimitedPair(Of L, R)) As String
         Return Value.ToString()
  End Operator

  Public Overrides Function ToString() As String
        Return _
            Me.m_Left.ToString & _
            Delimiter & _
            Me.m_Right.ToString
  End Function

 

Okay, so at this point, we've just removed the late binding calls, because we have the framework where all things derive from object, and hence have the .ToString method

 

I still like the LateCType method Cameron came up with, but like this, I would also try to avoid it ;)  And definetly try to avoid using shared methods on instances.  It's always preferable to use that isntance and hence call an instance method, not a Shared method.

 

 

 

 

 

 

 

 

 

Filed under:

Comments

# re: late bound conversions with generics !

Friday, August 05, 2005 7:31 PM by bill

Wait, wait, wait. Maybe I was sick that day in class, but why again are Shared methods to be avoided? Isn't it the other way around? i.e., defining a derived class where the Shared methods of the base class would be dangerous to call?