Click here to Skip to main content
15,880,972 members
Articles / Programming Languages / Visual Basic
Article

Cheat Sheet - Casting in VB.NET and C#

Rate me:
Please Sign up or sign in to vote.
4.56/5 (73 votes)
22 Sep 2003Public Domain2 min read 967K   94   42
Describes several casting and type related operations in VB.NET and C#.

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:

    VB.NET
    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():

    VB.NET
    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:

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

    VB.NET
    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:

    VB.NET
    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:

    C#
    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:

    C#
    Form f = (Form)a.b;

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

    C#
    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:

    C#
    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:

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

    C#
    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:

    C#
    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


Written By
Architect AREBIS
Belgium Belgium
Senior Software Architect and independent consultant.

Comments and Discussions

 
Generaldifference VB/C# in compile-time vs run-time error Pin
Alexis Rzewski7-Feb-07 4:51
Alexis Rzewski7-Feb-07 4:51 
QuestionHow about casting arrays Pin
Eric P Schneider19-Mar-05 8:57
Eric P Schneider19-Mar-05 8:57 
AnswerRe: How about casting arrays Pin
collinsauve7-Aug-08 3:28
collinsauve7-Aug-08 3:28 
GeneralToString Pin
George_Seremetidis28-Sep-04 13:40
George_Seremetidis28-Sep-04 13:40 
GeneralDon't Forget System.Convert.ChangeType Pin
Shaun Hayward29-Jun-04 7:35
Shaun Hayward29-Jun-04 7:35 
GeneralRe: Don't Forget System.Convert.ChangeType Pin
skjagini6-Sep-05 2:56
skjagini6-Sep-05 2:56 
JokeRe: Don't Forget System.Convert.ChangeType Pin
Artur M.7-Dec-06 21:45
Artur M.7-Dec-06 21:45 
GeneralProblems with casting objects Pin
simbakid3-Mar-04 3:04
simbakid3-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.
<br />
public static BaseDAO newInstance (DAOAssembly cAssembly, string strProviderID)<br />
{<br />
  // lookup instance<br />
  BaseDAO cDAO = m_cManager.lookup(cAssembly, strProviderID);<br />
<br />
  if (cDAO != null)<br />
  {<br />
    Console.WriteLine("Created DAO Instance");<br />
  }<br />
  else<br />
  {<br />
    Console.WriteLine("Failed to create specified DAO handler");<br />
  }<br />
<br />
  // initialise instance<br />
  // TODO:<br />
<br />
  return cDAO;<br />
}


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

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


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

<br />
Created DAO Instance<br />
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:

<br />
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? Pin
FruitBatInShades26-Jan-04 5:36
FruitBatInShades26-Jan-04 5:36 
GeneralPlease add pointers to the next update! Pin
Anonymous4-Oct-03 13:20
Anonymous4-Oct-03 13:20 
GeneralOK, but could be better Pin
David Bennett30-Sep-03 4:23
David Bennett30-Sep-03 4:23 
GeneralInformative Pin
Nish Nishant23-Sep-03 20:14
sitebuilderNish Nishant23-Sep-03 20:14 
GeneralComments Pin
Nick Seng23-Sep-03 15:21
Nick Seng23-Sep-03 15:21 
GeneralGood Pin
dog_spawn23-Sep-03 13:14
dog_spawn23-Sep-03 13:14 
GeneralRe: Good Pin
Furty23-Sep-03 13:36
Furty23-Sep-03 13:36 
GeneralRe: Good Pin
dog_spawn24-Sep-03 6:34
dog_spawn24-Sep-03 6:34 
GeneralRe: Good Pin
Rudi Breedenraedt25-Sep-03 5:22
Rudi Breedenraedt25-Sep-03 5:22 
GeneralRe: Good Pin
dog_spawn25-Sep-03 6:52
dog_spawn25-Sep-03 6:52 
GeneralRe: Good Pin
peterchen29-Sep-03 6:29
peterchen29-Sep-03 6:29 
GeneralRe: Good Pin
dog_spawn29-Sep-03 6:34
dog_spawn29-Sep-03 6:34 
GeneralRe: Good Pin
peterchen29-Sep-03 11:19
peterchen29-Sep-03 11:19 
GeneralRe: Good Pin
dog_spawn29-Sep-03 11:23
dog_spawn29-Sep-03 11:23 
GeneralRe: Good Pin
peterchen29-Sep-03 12:26
peterchen29-Sep-03 12:26 
GeneralRe: Good Pin
dog_spawn29-Sep-03 13:53
dog_spawn29-Sep-03 13:53 
GeneralRe: Good Pin
Rocky Moore23-Sep-03 14:14
Rocky Moore23-Sep-03 14:14 

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.