Is there a way to deny downcast of Base to Derived when Base is holding an instance of Derived? By default it's allowed.
Public Class Base
End Class
Public Class Derived
Inherits Base
End Class
Public Class Program
Public Shared Sub Main()
TakesOnlyBase(New Derived)
End Sub
Public Shared Sub TakesOnlyBase(ByVal b As Base) 'Not allowed to make changes in Derived part on the instance
Dim d As Derived = CType(b, Derived) 'it works since the variable `b` is holding an instance of Derived. How to forbid this cast?
'...
End Sub
End Class
The easiest way would be implement conversion function in Derived and just throw an exception.
Public Shared Widening Operator CType(ByVal b As Base) As Derived 'Compiler error: Conversion operators cannot convert from a base type.
Throw New System.Exception("Not allowed")
End Operator
But conversion from a base type is not allowed. Any other possibilities to override default conversion?
Any other solutions? Thanks for your help.