Click here to Skip to main content
6,594,432 members and growing! (15,194 online)
Email Password   helpLost your password?
Platforms, Frameworks & Libraries » .NET Framework » General     Beginner License: A Public Domain dedication

Cheat Sheet - Casting in VB.NET and C#

By Rudi Breedenraedt

Describes several casting and type related operations in VB.NET and C#.
C#, VB, Windows, .NET 1.0, .NET 1.1, Visual Studio, Dev
Posted:22 Sep 2003
Views:461,380
Bookmarked:61 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
56 votes for this article.
Popularity: 7.34 Rating: 4.20 out of 5

1
3 votes, 5.4%
2
8 votes, 14.3%
3
16 votes, 28.6%
4
29 votes, 51.8%
5

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


Member
Rudi is a Technical Architect at RealDolmen.
Occupation: Architect
Company: RealDolmen
Location: Belgium Belgium

Other popular .NET Framework articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 33 (Total in Forum: 33) (Refresh)FirstPrevNext
GeneralA note about as PinmemberWjousts5:16 24 Jul '09  
GeneralConverting Variables PinmemberSashoJ8:32 29 Jun '09  
GeneralRe: Converting Variables PinmemberWjousts5:15 24 Jul '09  
GeneralMissing a lot PinmemberJoshMouch15:27 25 Feb '07  
Generaldifference VB/C# in compile-time vs run-time error PinmemberAlexis Rzewski5:51 7 Feb '07  
GeneralHow about casting arrays Pinmembereschneider1009:57 19 Mar '05  
GeneralRe: How about casting arrays Pinmembercollinsauve4:28 7 Aug '08  
GeneralToString PinmemberGeorge_Seremetidis14:40 28 Sep '04  
GeneralDon't Forget System.Convert.ChangeType PinmemberShaun Hayward8:35 29 Jun '04  
GeneralRe: Don't Forget System.Convert.ChangeType Pinmemberskjagini3:56 6 Sep '05  
JokeRe: Don't Forget System.Convert.ChangeType PinmemberArtur M.22:45 7 Dec '06  
GeneralProblems with casting objects Pinmembersimbakid4:04 3 Mar '04  
GeneralDifference between DirectCast and Ctype? PinmemberFruitBatInShades6:36 26 Jan '04  
GeneralPlease add pointers to the next update! PinsussAnonymous14:20 4 Oct '03  
GeneralOK, but could be better PinsussDavid Bennett5:23 30 Sep '03  
GeneralInformative PineditorNishant S21:14 23 Sep '03  
GeneralComments PinmemberNick Seng16:21 23 Sep '03  
GeneralGood Pinmemberdog_spawn14:14 23 Sep '03  
GeneralRe: Good PinmemberFurty14:36 23 Sep '03  
GeneralRe: Good Pinmemberdog_spawn7:34 24 Sep '03  
GeneralRe: Good PinmemberRudi Breedenraedt6:22 25 Sep '03  
GeneralRe: Good Pinmemberdog_spawn7:52 25 Sep '03  
GeneralRe: Good Pinsupporterpeterchen7:29 29 Sep '03  
GeneralRe: Good Pinmemberdog_spawn7:34 29 Sep '03  
GeneralRe: Good Pinsupporterpeterchen12:19 29 Sep '03  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 22 Sep 2003
Editor: Nishant Sivakumar
Copyright 2003 by Rudi Breedenraedt
Everything else Copyright © CodeProject, 1999-2009
Web20 | Advertise on the Code Project