Runtime InvalidCastException with Implicit Cast Operator

I have a C # library that internal clients configure using VB.Net

Their scripts are thrown InvalidCastException

where they really shouldn't.

So the code is something like this (greatly simplified):

//C#3
public class Foo {

    public static implicit operator Foo ( Bar input )
    { 
        return new Foo( input.Property1, input.Property2 ); 
    }
}

      

Then in their VB.Net (again oversimplified):

Dim fc = New FooCollection()
Dim b as Bar = GetBar()

fc(fooIndex) = b 'throws InvalidCastException at runtime!

      

If I add a breakpoint inside the implicit / expansion operator, it never reached.

If I remove the implicit statement, it won't compile.

If I execute the equivalent statement in C #:

var fc = new FooCollection();
Bar b = GetBar();

fc[fooIndex] = b //it works!

      

Strange - it looks like the VB.net compiler can find the translation operator, but it got lost at runtime. Surely VB and C # IL will be pretty similar here?

VB.net code is dynamically compiled - compilation occurs when the user first logs into the application. it compiles as VB.Net against .Net 3.5 and I am not using COM interop.

Any ideas?

+2


source to share


1 answer


First, I would try to mark the C # assembly as CLSCompliant(true)

to see if this generates warnings on implicit operator Foo

.

Yeah, here it is:



The problem is that VB.NET just doesn't call the functions op_Implicit

/ op_Explicit

displayed by the C # code. You can see what under the cover is being used ICovertible

to perform all of its transformations.

+1


source







All Articles