Difference Between DirectCast and TryCast

Generally while doing our program in VB.NET or any language whatsoever, we come across some situation where we are in Dilemma of having more than one solution of a single problem. We think thoroughly of our knowledge base, search the Internet to get which one will be the best logic discuss with seniors or otherwise do random choice or anything. As a programmer, I always do face the problem. Let us take the example of casting in .NET.

We know, VB.NET always include Microsoft VisualBasic Namespace for your application internally, and you cannot remove the reference to that or even you don't find the namespace in the References list. This is because while you do programming with Visual Basic, your application would be enriched with some of the functionalities that Microsoft VisualBasic namespace have within your program. Take for instance Val, CStr, CInt etc. All of them are written inside Microsoft VisualBasic namespace and is included automatically in our program. They are are acting as language helpers in your program.

DirectCast:

Let us try to write one of this language helpers ourself.

Public Function CustomCInt(ByVal value as Object) as Integer
if typeof Value is Integer then
Dim i as Integer = CustomCInt(Value)
Return i
End Function

After viewing the above code you must be laughing like hell on what I have done with this. Actually my motive is to show you how difficult is to write a helper yourself without using CLR supported casting feature. Here comes the case of DirectCast. While using CInt, CStr, or CType you are actually calling a function which does similar to what I have written. Means it first checks if the type is convertable or not through Typeof Operator and then casts to appropriate Type.
DirectCast is the Simple CLR typecasting feature which you can use when you are sure about the cast. It avoids the sequence of checking in the helper Functions. Now you can write your own Helper Function like this:

Public Function CustomCInt(ByVal value as Object) as Integer
If TypeOf value is Integer then
Dim i as Integer = DirectCast(value,Integer)
Return i
End if
End Function

Now it looks great, Isnt it. Actually this is how .NET helpers are made, CType checks if the object corresponds to the Type specified and then DirectCast it to return the Converted Type Data. DirectCast is the most simple and CLR supported TypeCast feature that will cast properly if it is with appropriate type or otherwise throws an error.

TryCast:

Now going further, Lets start with TryCast. After knowing DirectCast you may wonder what exactly the TryCast is. Actually TryCast operator of VisualBasic is equivalent to 'is' operator of C#. TryCast is useful in some situations too.
Let us take the following example

Public Function CustomCheck(ByVal value as Object) as IDBConnection
If TypeOf value is IDBConnection then
Dim i as IDBConnection = DirectCast(value,IDBConnection)
Return i
End if
End Function

In this example, we are telling the CLR to check the type of Value that we passed to the Function using TypeOf function in the If statement. If it enters into the IF we can confirm that the value implements IDBConnection. But CLR doesn't knows it. Thus on the very next step, it will check if the value actually an implementation of IDBConnection again. Thus we are running redundant code. Using TryCast we can avoid that.
We may write

Dim i as IDBConnection = TryCast(value,IDBConnection)


This will direct the CLR to check if value implements IDBConnection and if so, it will convert it directly. Thus we removed Redundant code.
TryCast will store nothing if it cannot cast the value. In case of using TryCast for primitive types, it will store the value of initialization as output if it cannot convert. For Instance, conversion to integer will give you Zero(0) etc.

Hope you understand the two simple operators of Visual Basic. Don't forget to Comment on the topic. Thanks.
Shout it Submit this story to DotNetKicks Bookmark and Share
Read Disclaimer Notice

8 comments:

abhishek2434 said...

Yah.. I dont know this .... very good idea.

Mandar Jambotkar said...

Thanks for the detail elaboration of the concept.

But I still have one doubt, i.e. If TryCast feature is available then is DirectCast really required ?

As TryCast does the needfull(i.e. Check for TypeOf and then convert OR else set to default value like 0 for integer, then when should DirectCast be used.

Sorry to bother you, but I'm still confused !

Abhishek Sur said...

Well Mandar,
You are right, if there is TryCast which checks for Type. Well the thing is that sometimes there are some requirement where we need to throw error if it doesn't cast properly.
And another thing, DirectCast is more primitive Cast Feature in .NET. In every casting, it calls DirectCast, on the other hand Trycast is just a Derivative from DirectCast with some inclusion of features.
Thanks for your concern, really we could check for null after doing the Cast using Trycast and throw errors, but why not we use DirectCast directly. DirectCast is just the TypeCast feature in C# while TryCast is 'as' operator in C#. Both are included.

In .NET there are lots of features which is not really needed, but still included.

Thank you for your Comment.
Happy new Year

Anonymous said...

TryCast and DirectCast are actually both CLR primitives (isinst and castclass, respectively, in MSIL). "Typeof X is T", incidentally, is a wrapper around isinst.

ChristianM said...

thanks for sharing this. Good explanation of TryCast.. and good ranking in google score when searching for directcast vs trycast.

Abhishek Sur said...

You are most welcome budd.

Anonymous said...

Good Explanation ,my query is like that,
i read on internet ,use CType instead of DirectCast for VB.Net, even though Performance of DirectCast Cast is faster that CType.

Why it is insist that ?

Here is following link
http://www.codeproject.com/KB/vb/DirectcastVsCtype.aspx


Looking forward for your Positive Reply !

Regards
Shubhank Upadhyay

Abhishek Sur said...

See, If you are 100% sure that the cast is valid, then only you can use DirectCast. DirectCast will actually throw an error if the cast is not valid.

CType is actually changes the type. So it is almost similar, but a better approach when you are not sure about the cast.

Post a Comment

Please make sure that the question you ask is somehow related to the post you choose. Otherwise you post your general question in Forum section.

Author's new book

Abhishek authored one of the best selling book of .NET. It covers ASP.NET, WPF, Windows 8, Threading, Memory Management, Internals, Visual Studio, HTML5, JQuery and many more...
Grab it now !!!