Last week, I was asked a question, "I have 2 different classes with almost same properties, not derived, but I cannot convert one to other, How do I?" As I have not written since long about anything, I thought I will go with Narrowing (and Widening) keywords provided by visual basic to overload operator. So here is one example:

Suppose there are 2 classes: 


Public Class FootBall

    Sub New(ByVal FootBallRadius As Double)

        _Radius = FootBallRadius

    End Sub

    Private _Radius As Double

    Public Property Radius() As Double

        Get

            Return _Radius

        End Get

        Set(ByVal value As Double)

            _Radius = value

        End Set

    End Property

 

End Class

 

Public Class Circle

    Private _Radius As Double

    Sub New(ByVal CircleRadius As Double)

        _Radius = CircleRadius

    End Sub

 

    Public Property Radius() As Double

        Get

            Return _Radius

        End Get

        Set(ByVal value As Double)

            _Radius = value

        End Set

    End Property

End Class


They are similar, lets create a new instance of FootBall


Dim FT As New FootBall(23)

Since our Circle class also has radius, we want to convert football to circle for some reason

Dim cir As Circle = CType(FT, Circle)

 

Nope cand do that unless we define narrowing operator in Circle class, lets do that

 

Public Class Circle

.......................

.........................

Public Shared Narrowing Operator CType(ByVal FB As FootBall) As Circle

        Dim cir As New Circle(0)

        cir.Radius = FB.Radius

        Return cir

    End Operator

 

End Class

 

Now if you try converting, you get no error

 

Dim FT As New FootBall(23)

        Dim cir As Circle = CType(FT, Circle)

        Debug.WriteLine(cir.Radius)

 

easy peasy lemon squeezy!!!

 Happy coding :)