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   
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.
GeneralRe: Goodmemberdog_spawn24 Sep '03 - 6:34 
You seem to have missed my point. I will try to explain myself better.
 
Obviously using C# requires casting. But that is because most of the framework is not designed as well as it could be. My point is about design not about the way the framework happens to be setup Smile | :)
 
Most of the time we only cast because C# doesn't allow us to make specialized collections easily enough yet. 'generics' will solve that hopefully.
 
No plugin architecture ever needs casting. Any plugin object inherits some interface. Obviously a give program only knows about the interface. If you end up casting using plugin objects your interfaces need redesigning Confused | :confused:
GeneralRe: GoodmemberRudi Breedenraedt25 Sep '03 - 5:22 
First, thanks for the compliment!
 
Concerning your good OO design (btw, I don't know if C++ purists are by definition to be considered as OO purists, but please, let's not start that discussion here...D'Oh! | :doh: ):
 
Casting is in my opinion not a matter of design. Casting originates from the fact that the implementation is done in a strong-typed language. Would you implement in a purely object-oriented language as SmallTalk, then you would never have to cast, since it does no typechecking, and even does not know what casting is...
 
Now, should you design in such a way that casting will not be necessary in an implementation language ? My answer would again be no. Good OO designs are caracterised by their good distribution of responsibilities. Is it a good distribution of responsibility to have the superclass know about all it's (current but also future !?!) subclasses, since it should provide GetAsSubclass methods for each one of them ? I believe the contrary. By the way, as I pointed out, you can only provide GetAs methods for known (=current) subclasses, so you disallow extension by subclassing by 3rd parties. Wasn't OO meant to be extended that way ?
 
Consequently, if C# requires casting, it's not due to bad design (although design could have been better), but due to it's strong-typed character.

GeneralRe: Goodmemberdog_spawn25 Sep '03 - 6:52 
Rudi Breedenraedt wrote:
Consequently, if C# requires casting, it's not due to bad design (although design could have been better), but due to it's strong-typed character.
 
C# is a strongly typed language. However the collections are not, hence my comments about bad design.
 
I think you have got mixed up here D'Oh! | :doh: You do not need casting with a strongly typed language. That is the point of types. C# requires casting so frequently because of the bad design of the collections.
 
Rudi Breedenraedt wrote:
I believe the contrary
 
I agree it is bad design to have GetAsSubclass method Smile | :) However that is a better solution than casting. This problem can be solved by good design. For example GetElementsByTagName in the XML part of the framework should return a list of XmlElements, not a list of XmlNodes as it currently does.
GeneralRe: Goodmemberpeterchen29 Sep '03 - 6:29 
Casting in C# is nothing else than querying for another interface. The cast is verified to be valid. So what?
 

"Vierteile den, der sie Hure schimpft mit einem türkischen Säbel."

sighist | Agile Programming | doxygen

GeneralRe: Goodmemberdog_spawn29 Sep '03 - 6:34 
Heh, well 'So what?' is a perfectly practical point of view Smile | :) It kind of misses the point but it's less hard work.

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