Class boxed in an object

  • Thread starter Thread starter Nio
  • Start date Start date
N

Nio

Hello, I have a class implementing comparison operators and cast operators
(CType) .
This class called MyOpTest

Now look at this code:

Dim MyOp As New MyOpTest
Dim data As String = MyOp 'OK no error, MyOpTest
implements "Shared narrowing operator CType(byval a As MyOpTest) As String"
Dim obj As Object = New MyOpTest 'now instance is boxed into an
object type

Dim Result as Boolean = Cbool(obj < 2) 'OK no error MyOpTest implements
"Shared operator < (byval p1 as Object, byval p2 As Object) As Boolean"
Dim data2 As String = obj 'This failed!! casting
exception from MyOpTest!! to String

So why when instance is boxed into object, casting operations are not called
and comparison operators are called ?

Is there any solution ? (a way to implicit unbox object type) ?
Thanks for your answers.
 
Nio said:
Hello, I have a class implementing comparison operators and cast operators
(CType) .
This class called MyOpTest

Now look at this code:

Dim MyOp As New MyOpTest
Dim data As String = MyOp 'OK no error, MyOpTest
implements "Shared narrowing operator CType(byval a As MyOpTest) As String"

No, it doesn't work. Option Strict Off? Switch is it on, first. Otherwise
you can throw away all type awareness. It's a _narrowing_ operator, which means,
it could fail at runtime.
Dim obj As Object = New MyOpTest 'now instance is boxed into an
object type

Dim Result as Boolean = Cbool(obj < 2) 'OK no error MyOpTest implements
"Shared operator < (byval p1 as Object, byval p2 As Object) As Boolean"
Dim data2 As String = obj 'This failed!! casting
exception from MyOpTest!! to String

So why when instance is boxed into object, casting operations are not called
and comparison operators are called ?

CBool is an explicit cast. The compiler trusts you.
Whereas "Dim data2 As String = obj" requires an implicit cast/conversion. Casting
from Object to String is not defined/allowed.
Is there any solution ? (a way to implicit unbox object type) ?

I don't think so.
 
When I wrote the 2nd part of my answer, I wasn't aware of Option Strict Off, yet.
I misread it and assumed a compile time error but you mentioned an exception. Sorry,
my fault.

Well, with Option Strict On, you don't get an exception, so I think this changed
the situation. But, you can also not write

Dim data2 As String = CType(obj, String) 'failure

because it's the compiler that is responsible for making use of your own operator.
It's not used in this case because the expression type is Object, not MyOpTest.

So you'd have to write

Dim data2 As String = CType(DirectCast(obj, myoptest), String)
 
Back
Top