Click here to Skip to main content
Click here to Skip to main content

Cheat Sheet - Casting in VB.NET and C#

By , 22 Sep 2003
 

Introduction

This article describes several casting and type related operations in VB.NET and C#.

Casting in VB.NET

  1. By default in VB, casting is automatically done for you when you assign objects to variables. The objects are then automatically casted to the variables' type.

    This behaviour can be influenced by an option line on top of your code file:

    Option Strict On
    Option Strict Off
    

    When on, casting is strict and not automatic.

  2. Explicit casting can be done with the cast operator CType() or DirectCast():

    textbox = CType(obj, TextBox)
    textbox = DirectCast(obj, TextBox)
    

    The difference between the two keywords is that CType succeeds as long as there is a valid conversion defined between the expression and the type, whereas DirectCast requires the run-time type of an object variable to be the same as the specified type. If the specified type and the run-time type of the expression are the same, however, the run-time performance of DirectCast is better than that of CType. DirectCast throws an InvalidCastException error if the argument types do not match.

  3. Testing if an object is of a particular type, can be done with the TypeOf...Is operator:

    If TypeOf obj Is TextBox Then...
    
  4. Obtaining a System.Type object for a given type can be done with the GetType operator:

    Dim t As System.Type
    t = GetType(String)
    MessageBox.Show(t.FullName)
    
  5. Obtaining a System.Type object for a given object can be done with the GetType method:

    Dim t as System.Type
    t = obj.GetType()
    MessageBox.Show(t.FullName)
    

Casting in C#

  1. C# is a strictly typed language. Whenever types don't match, casting is necessary.

    Regular casting in C# follows the C(++) and Java syntax:

    string s = (string)obj;
    

    The casting operator applies to the complete chain on the right of it, so in the following example, not a, but a.b is casted to a Form:

    Form f = (Form)a.b;
    

    To cast parts of the chain, use brackets. In the following example, obj is casted to a Form:

    string s = ((Form)obj).Text;
  2. C# knows an additional casting operator: as.

    The as operator is like a cast except that it yields null on conversion failure instead of raising an exception. In the following situation, btn gets the value null:

    Object obj = new TextBox();
    Button btn = obj as Button;
    
  3. Testing if an object is of a particular type, can be done with the is operator:

    if (obj is TextBox) {...}
    
  4. Obtaining a System.Type object for a given type can be done with the typeof operator:

    System.Type t;
    t = typeof(String);
    MessageBox.Show(t.FullName);
    
  5. Obtaining a System.Type object for a given object can be done with the GetType method:

    System.Type t;
    t = obj.GetType();
    MessageBox.Show(t.FullName);
    

License

This article, along with any associated source code and files, is licensed under A Public Domain dedication

About the Author

Rudi Breedenraedt
Architect Wolters Kluwer Belgium
Belgium Belgium
Member
Rudi is a Software Architect at Wolters Kluwer Belgium.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberHeaven202018 Mar '13 - 3:11 
good one
GeneralMy vote of 4memberbatres-sc10 Mar '13 - 14:31 
Very Good friend!
GeneralMy vote of 5memberJGeZau22 Oct '12 - 8:19 
Excatly what I was looking for. Great article
GeneralMy vote of 5memberMcwatt775 Oct '10 - 14:51 
This article is the bomb!
Everything I needed.
Short and to the point.
GeneralMy vote of 4memberrichardhenwood13 Jul '10 - 22:30 
detailed explaination but does not serve the purpose of a quik refrence as i'd expect from cheat sheet
GeneralHimembermanchisrikanth10 Jun '10 - 2:22 
Poke tongue | ;-P
GeneralA note about asmemberWjousts24 Jul '09 - 4:16 
Note: the as keyword will only work with reference types since value types can't be null.
GeneralConverting VariablesmemberSashoJ29 Jun '09 - 7:32 
Please answer:
Is there a way to Convert variable with type as a String parameter?
Can you write a function like this:
a = MyTryCast(variable as Object, SystemType As String)
and then use it like:
a = MyTryCast("12.13", "System.Decimal")
 
without use of
 
Select Case SystemType
Case "System.String"
return CType(variable, String)
...
GeneralRe: Converting VariablesmemberWjousts24 Jul '09 - 4:15 
You can get a type from a string using Type.GetType:
 
http://msdn.microsoft.com/en-us/library/w3f99sx1.aspx[^]
GeneralMissing a lotmemberJoshMouch25 Feb '07 - 14:27 
No offense, but this article is missing a lot. Each C# & VB.Net casting feature has an equivalent.
 
For example:
The VB.Net's equivalent to C#'s "as" is TryCast()
Generaldifference VB/C# in compile-time vs run-time errormemberAlexis Rzewski7 Feb '07 - 4:51 
one BIG difference between C# and VB:
 
C# compiler will never allow
 
int myInt = (int) "3";
 
VB.NET compiler, even with Option Strict ON will always allow
 
Dim myInt as Integer = CType ("3", Integer)
 
Both languages understand the .NET class System.Convert:
 
myInt = System.Convert.ToInt32("3")

QuestionHow about casting arraysmembereschneider10019 Mar '05 - 8:57 
How about and example on casting arrays.
 
Thanks
 
Schneider
AnswerRe: How about casting arraysmembercollinsauve7 Aug '08 - 3:28 
I would like to figure out how to do this to.
This is something like what I would like to do...
 
Public Sub SortMyArray(aValues() as Object)
  if typeof aValues is String() then
    SortStrings(directcast(aValues,string())
  elseif typeof aValues is SomeOtherObject() then
    SortOtherObjects(directcast(aValues,SomeOtherObject())
  end if
End Sub
 
Private Sub SortStrings(asValues() as String)
  'Do the sort
End Sub
Private Sub SortOtherObjects(aValues() as SomeOtherObject)
  'Do the sort
End Sub

GeneralToStringmemberGeorge_Seremetidis28 Sep '04 - 13:40 
I prefer to use ToString rather than CType for certain things. ToString will return an empty string if a column is a NULL in a DataRow. CType will throw an exception on a NULL.
GeneralDon't Forget System.Convert.ChangeTypememberShaun Hayward29 Jun '04 - 7:35 
Good article.
 
Another important conversion method is the System.Convert class's ChangeType method - especially when you're using Reflection.
 
The problem with GetType is that the second parameter must accept the name of the type but cannot accept an instance of System.Type (at least no way that I could find).
 
So you can't do the following:
 
obj2 = CType(SomeValue, obj1.GetType)
 
Confused | :confused:
 
This was a REAL problem when trying to convert strings to an EXACT datatype to use the SetValue method in Reflection. The solution:
 
obj2 = System.Convert.ChangeType(SomeValue, obj1.GetType)
 
Cool | :cool:
 
Something worth investigating and possibly adding to the article.
GeneralRe: Don't Forget System.Convert.ChangeTypememberskjagini6 Sep '05 - 2:56 
awesome
JokeRe: Don't Forget System.Convert.ChangeTypememberArtur M.7 Dec '06 - 21:45 
Thank you for pointing out Convert.ChangeType function. This is more important for me then entire article. Smile | :) Rose | [Rose]
 
P.S. However, this function has one limitation- value has to implement IConvertible interface Frown | :(
GeneralProblems with casting objectsmembersimbakid3 Mar '04 - 3:04 
I have a problem in my code with regard casting. I have a base class object called BaseDAO, a subclass is created from this called CustomerRowSet. I have a function which, through reflection, will create an instance of the subclass.

public static BaseDAO newInstance (DAOAssembly cAssembly, string strProviderID)
{
// lookup instance
BaseDAO cDAO = m_cManager.lookup(cAssembly, strProviderID);
 
if (cDAO != null)
{
Console.WriteLine("Created DAO Instance");
}
else
{
Console.WriteLine("Failed to create specified DAO handler");
}
 
// initialise instance
// TODO:
 
return cDAO;
}

 
I make a call to the newInstance function and test the type of the returned object, thus:
 

DAOAssembly x = new DAOAssembly("DAOTest.dll", "d:", "ds.xml", "d:", "TEST");
Object o = CustomerRowSet.newInstance(x, "SELECT_CUSTOMERS");
if (o is DAOTest.CustomerRowSet)
{
Console.WriteLine("Object is of correct type");
}
else
{
System.Type t;
t = o.GetType();
Console.WriteLine(t.FullName);
}

 
Upon return, execution branches into the else statement and not the if statement, but the output from code is:
 

Created DAO Instance
DAOTest.CustomerRowSet

 
This shows that the returned object is of the correct type yet doesn't execute the if branch of the code. In addition, if I try the following code:
 

CustomerRowSet rs = (CustomerRowSet)CustomerRowSet.newInstance(x, "SELECT_CUSTOMERS");

 
I get an InvalidCastException.
 
Grateful for any suggestions or information, many thanks in advance.
 
Chris.

QuestionDifference between DirectCast and Ctype?memberFruitBatInShades26 Jan '04 - 5:36 
If the specified type and the run-time type of the expression are the same, however, the run-time performance of DirectCast is better than that of CType.
So which function gives the best performance under all circumstances? Can you give an example of what type of conversions cause DirectCast to throw!
 
Thanks
GeneralPlease add pointers to the next update!sussAnonymous4 Oct '03 - 13:20 
Please add pointers in the next update, they are still used in C# and casting can be done with them. I am particularly having trouble with pointers in my COM Interop which involves casting.
GeneralOK, but could be bettersussDavid Bennett30 Sep '03 - 4:23 
>>>C# is a strictly typed language. Whenever types don't match, casting is necessary.
 
This is simply not true. C# allows you to upcast and perform implicit conversions (eg double to int) without needing a cast.
 
The whole issue of implicit vs explicit is not mentioned.
 
The existence of a range of other conversion functions (CInt, CDbl, etc) is ignored. Likewise the Convert functions, ToString(), etc.
 
I'll wait for V2.
GeneralInformativeeditorNishant S23 Sep '03 - 20:14 
Thanks Smile | :)
 
Nish
 

Extending MFC Applications with the .NET Framework [NW] (coming soon...)
Summer Love and Some more Cricket [NW] (My first novel)
Shog's review of SLASMC [NW]
Come with me if you want to live

GeneralCommentsmemberNick Seng23 Sep '03 - 15:21 
Where were you when I just started doing C# & VB.Net? Poke tongue | ;-P
 
Anyway, a couple of comments:
 
1) Your explaination of DirectCast isn't really clear. Maybe it would help if you showed some example.
 
2) I don't really see the difference for point 4 & 5.
 

Besides that good article. A lot of newbie would undoubtably find it helpfull Big Grin | :-D
 










Support Bone

GeneralGoodmemberdog_spawn23 Sep '03 - 13:14 
I liked the style of this article as you consider both C# and VB.NET. I learnt something new - I did not know about the as operator Smile | :)
 
Do any C++ purists agree with me when I say: casting is never needed in good OO design.
 
Even in an XML parser you don't need it. Consider a simple example: if you can always predict what nodes you might need to 'cast' into you can provide a function:
 
CommentElement Node::GetAsComment()
 
...where Node is the superclass of all Xml element nodes.
GeneralRe: GoodmemberFurty23 Sep '03 - 13:36 
dog_spawn wrote:
Do any C++ purists agree with me when I say: casting is never needed in good OO design.
 
Just off the top of my head, here are some examples where very good design in C# requires casting:
 
* Creating a plug-in architecture - try loading and instantiating dynamically assemblies without polymorphic reflection tests and casting.
 
* Using pretty much any of the Asynchronous programming methods in the FCL - all use boxing and un-boxing, which can't be done without casting.
 
* Adding queue items that return values to a the ThreadPool requires boxing and un-boxing, which again is casting.

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

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 23 Sep 2003
Article Copyright 2003 by Rudi Breedenraedt
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid