Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use TryCast instead of DirectCast?

Tags:

casting

vb.net

When I am trying to cast Object obj to Type T, if it can not be cast then there is something wrong.

And after I cast the object I will be looking for working with the cast object.

Rather I will be expecting to get an exception at the place where I will be casting it than say where I will be using that object.

In this sense, is it better to use DirectCast instead of TryCast? Or am I missing some other significance of using TryCast?

like image 484
Biswanath Avatar asked Dec 22 '08 07:12

Biswanath


People also ask

What is TryCast?

TryCast returns Nothing, so that instead of having to handle a possible exception, you need only test the returned result against Nothing . You use the TryCast keyword the same way you use the CType Function and the DirectCast Operator keyword.

What is DirectCast vb net?

You use the DirectCast keyword similar to the way you use the CType Function and the TryCast Operator keyword. You supply an expression as the first argument and a type to convert it to as the second argument. DirectCast requires an inheritance or implementation relationship between the data types of the two arguments.


2 Answers

(For C# developers, TryCast is similar to "as" and DirectCast is the equivalent of normal casting. As Mike pointed out in the comments, "as" works for nullable value types, but TryCast doesn't.)

If the value really should be a T, then DirectCast is indeed the right way to go - it fails fast, with an appropriate error.

TryCast is appropriate when it's legitimate for the target to be the "wrong" type. For instance, to get all the Button controls in a container, you could go through the control collection and try to cast each to Button. If it works, you do something with it - if it doesn't, you move on. (With LINQ you can just use OfType for this purpose, but you see what I mean...)

In my experience direct casting is appropriate more often than TryCast - although with generics I find myself casting a lot less often than I used to anyway.

like image 95
Jon Skeet Avatar answered Sep 20 '22 11:09

Jon Skeet


The only difference between the two is that, a TryCast will return a null if it fails, while a DirectCast will throw an exception.

These has implications on how you can handle your program. Personally I prefer not having to throw an exception if the possibility of an improper cast (e.g., text input boxes for user input being cast into numeric types) is pretty high.

like image 38
Jon Limjap Avatar answered Sep 20 '22 11:09

Jon Limjap