Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TryCast fails where DirectCast works (.NET 4.0)

I find this behavior of TryCast in .NET 4.0 / VS 2010 rather confusing.

In my understanding TryCast works like DirectCast, but will return Nothing instead of throwing an exception if a cast is not possible.

VS 2010 / .NET 4

?TryCast(CType(1, Object), String)
Nothing
?DirectCast(CType(1, Object), String)
"1"

VS 2008 / .NET 3.5

?TryCast(CType(1, Object), String)
Nothing
?DirectCast(CType(1, Object), String)
Cannot convert to 'String'.

The .NET 3.5 results are consistent with what I believe TryCast does... .NET 4 however is not.

Can someone please point me in the best direction to securely cast an object to String in .NET 4?

like image 496
motto Avatar asked Aug 19 '10 15:08

motto


1 Answers

Based on your code samples starting with the ? I'm guessing you're using the immediate window to perform your test correct? The problem with this approach is that the immediate window is an interpretation instead of an actual evaluation. This leaves it susceptible to subtle corner case bugs and this is indeed one of them.

If you take your sample code and add it to a simple VB.Net console application you'll find that the 2010 behavior is identical to the 2008 behavior (throws an exception).

EDIT

So why did this regression happen? In 2010 I completely rewrote the VB EE debugging engine (expression evaluator). The older code base I inherited was simply too costly to maintain anymore. To the point that adding new features to the engine was more expensive that rewriting it from scratch with a better architecture that included the new features.

As said before debugging evaluations is an interpretation more than an execution of code. It forces the duplication of some algorithms between the EE and CLR / Compiler. One of the areas where duplication occurs is in the casting logic. There is no way to ask the CLR debugger to cast a debug time object, it's the responsibility of the EE to determine if the language specified cast is indeed valid.

The old EE casting logic had numerous bugs (especially in the area of generics and arrays). The newer infrastructure conforms very closely to the CLR guidelines. However you'll never have 100% parity because it would disallow very useful expressions in the EE (I may write a blog post on this in the future). But for most cases the behavior holds.

In this particular instance I added a subtle bug which allows for a DirectCast of a value which is typed to Object to use VB's Runtime Conversion operators vs. the specified behavior which only allows for CLR conversions. Hence this conversion succeeds where it should fail.

like image 197
JaredPar Avatar answered Sep 20 '22 04:09

JaredPar