Unboxing/Nullable InvalidCastException - by Dan Orchard

Status : 

  By Design<br /><br />
		The product team believes this item works according to its intended design.<br /><br />
		A more detailed explanation for the resolution of this particular item may have been provided in the comments section.

Sign in
to vote
ID 636024 Comments
Status Closed Workarounds
Type Bug Repros 0
Opened 1/13/2011 4:14:41 PM
Access Restriction Public


This code produces an InvalidCastException:

Dim o As Object = CType(2, Int64?)
Dim i As Int32?
i = o

Whereas a very similar piece of code, minus object boxing, succeeds:

Dim l As Int64? = 2
Dim i As Int32?
i = l
Sign in to post a comment.
Posted by Microsoft on 4/6/2011 at 4:37 PM
Hi Dan. Thanks for filing the bug.

Conceptually, I think of this as a "late binder" issue...

* In the static case which works, the compiler itself has all the information it needs to know how to implement the conversion

* But in the "Object" case which fails, the compiler doesn't. It has to farm the work out to a helper function which resides in Microsoft.VisualBasic.dll. This helper function would do a run-time check on the type residing in that object, and would call into the appropriate conversion routine.

These helper functions reside in Microsoft.VisualBasic.dll. We've only implemented the core conversions to primitive types. We haven't implemented arbitrary nullable conversions (as in this case), nor user-defined conversions.

In general the helper functions are a kind of heavy hammer -- especially with the new VBCore feature ("/vbruntime*"). We'd only consider adding to them if there was a strong pressing need. I think this case falls into the "nice to have" rather than "strong pressing need" case, so we wouldn't want to add anything.

I wrote more about the issue of Microsoft.VisualBasic.dll, and of how faithfully the runtime binder can replicate what the compile-time binder does, here:

(Please reply to this bug or on the above web page if you disagree with that conclusion!)

Thanks again,

Lucian Wischik, VB language PM
Posted by Microsoft on 1/13/2011 at 5:15 PM
Thank you for your feedback, we are currently reviewing the issue you have submitted. If this issue is urgent, please contact support directly(http://support.microsoft.com)