Otherwise
(1)
MyOpTest
(1)
Result
(1)
DirectCast
(1)
CType
(1)
MyOp
(1)
Cbool
(1)
Implements
(1)

Class boxed in an object

Asked By Nio
21-Nov-09 03:49 AM
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
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 schrieb:No, it does not work. Option Strict Off?

Armin Zingler replied to Nio
21-Nov-09 06:31 AM
Nio schrieb:

No, it does not work. Option Strict Off? Switch is it on, first. Otherwise
you can throw away all type awareness. it is a _narrowing_ operator, which means,
it could fail at runtime.


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.


I do not think so.


--
Armin

Armin Zingler schrieb:When I wrote the 2nd part of my answer, I was not aware

Armin Zingler replied to Armin Zingler
21-Nov-09 06:58 AM
Armin Zingler schrieb:

When I wrote the 2nd part of my answer, I was not 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 do not 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 is the compiler that is responsible for making use of your own operator.
it is not used in this case because the expression type is Object, not MyOpTest.

So you would  have to write

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



--
Armin
Post Question To EggHeadCafe