Click here to Skip to main content
13,868,387 members
Click here to Skip to main content
Add your own
alternative version

Tagged as


7 bookmarked
Posted 13 Jul 2009
Licenced CPOL

Difference Between DirectCast and TryCast

, 16 Jul 2009
Rate this:
Please Sign up or sign in to vote.
What is the 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 a dilemma of having more than one solution of a single problem. We think thoroughly about our knowledge base, search the Internet to get which one will be the best logic, discuss with seniors or otherwise make a 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 includes 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 are included automatically in our program. They are acting as language helpers in your program.


Let us try to write one of these language helpers ourselves.

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 it 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 convertible 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, isn't 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.


Now going further, let's begin 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 is 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!


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Abhishek Sur
India India
Did you like his post?

Oh, lets go a bit further to know him better.
Visit his Website : to know more about Abhishek.

Abhishek also authored a book on .NET 4.5 Features and recommends you to read it, you will learn a lot from it.

Basically he is from India, who loves to explore the .NET world. He loves to code and in his leisure you always find him talking about technical stuffs.

Working as a VP product of APPSeCONNECT, an integration platform of future, he does all sort of innovation around the product.

Have any problem? Write to him in his Forum.

You can also mail him directly to

Want a Coder like him for your project?
Drop him a mail to

Visit His Blog

Dotnet Tricks and Tips

Dont forget to vote or share your comments about his Writing

You may also be interested in...


Comments and Discussions

GeneralMy vote of 1 Pin
SmirkinGherkin16-Jul-09 6:52
memberSmirkinGherkin16-Jul-09 6:52 
GeneralMy vote of 1 Pin
VMykyt13-Jul-09 23:09
memberVMykyt13-Jul-09 23:09 
GeneralRe: My vote of 1 Pin
Abhishek Sur16-Jul-09 5:32
professionalAbhishek Sur16-Jul-09 5:32 
GeneralMy vote of 1 Pin
Klaus Luedenscheidt13-Jul-09 19:56
memberKlaus Luedenscheidt13-Jul-09 19:56 
GeneralRe: My vote of 1 Pin
Abhishek Sur16-Jul-09 5:32
professionalAbhishek Sur16-Jul-09 5:32 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web05 | 2.8.190214.1 | Last Updated 16 Jul 2009
Article Copyright 2009 by Abhishek Sur
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid