Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 36 ยท Syntax and Types

Option Strict and Type Conversions

Understand widening and narrowing conversions in Visual Basic .NET, why Option Strict On matters, and how to convert safely with CInt, CType, DirectCast, Convert and TryParse.

Programs constantly turn one type into another: text typed by a user into a number, a Double into an Integer, a base-class reference into a derived one. VB.NET is famous for being permissive about this. Out of the box (Option Strict Off) it silently converts between almost anything, which hides bugs. With Option Strict On the compiler tells you where a conversion might lose data or fail. This lesson explains the rules and the tools, so you can write code that is both convenient and safe. Listings are VB.NET (read-only); runnable C# stand-ins show the same .NET conversion behavior.

Widening and narrowing conversions

  • A widening conversion can never lose information: Integer to Long, Integer to Double, a derived class to its base class. These are implicit and always allowed.
  • A narrowing conversion might lose data or fail: Double to Integer, Long to Integer, Object to String, base class to derived class. With Option Strict On they need an explicit conversion.
VB
Option Strict On

Dim small As Integer = 42
Dim big As Long = small          ' widening: fine
Dim d As Double = small          ' widening: fine

Dim back As Integer = big        ' ERROR BC30512: implicit conversion from Long to Integer
Dim n As Integer = 3.7           ' ERROR: Double to Integer
Dim m As Integer = CInt(3.7)     ' OK: explicit, rounds to 4

With Option Strict Off those two errors vanish, and Dim n As Integer = "12" even converts a string at run time, or throws InvalidCastException if the text is not a number. That silent behavior is why every serious team turns Option Strict On. In Visual Studio set it in Project Properties, or in the .vbproj with <OptionStrict>On</OptionStrict> (see Project Structure and Compilation).

Option Strict On also bans late binding: calling a member on a variable declared as Object and resolving it at run time. You must cast to a real type first, so typos in method names become compile errors instead of run-time failures.

Explicit conversion functions

VB offers short conversion keywords, one per type:

Function Result Notes
CInt(x) Integer rounds to nearest, ties go to even (banker's rounding)
CLng, CShort, CByte integral types throw OverflowException when out of range
CDbl, CSng, CDec floating point / decimal
CStr(x) String
CBool(x) Boolean any non-zero number is True
CChar, CDate Char, Date
CObj(x) Object
CType(x, T) any type T general form; checks that a conversion exists
DirectCast(x, T) reference conversion no value conversion; fails if the object is not a T
TryCast(x, T) reference conversion returns Nothing instead of throwing

Rounding is an important detail: CInt(2.5) is 2 and CInt(3.5) is 4 (round half to even). To cut off the fraction use Math.Truncate, Int(x) (floors) or Fix(x) (truncates toward zero).

C# Stand-in (C#): rounding versus truncating

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Note that C#'s plain (int) cast truncates while VB's CInt rounds, a classic trap when porting code.

Parsing user input safely

Never trust text from users or files. CInt("abc") throws InvalidCastException (and Integer.Parse("abc") throws FormatException). Use TryParse, which returns a Boolean and fills an output variable:

VB
Dim input As String = Console.ReadLine()
Dim age As Integer

If Integer.TryParse(input, age) Then
    Console.WriteLine($"Next year you will be {age + 1}.")
Else
    Console.WriteLine("Please type a whole number.")
End If

Double.TryParse, Decimal.TryParse, Date.TryParse, Boolean.TryParse and Enum.TryParse(Of T) follow the same pattern. Numbers are parsed with the current culture by default: in a German locale "3,5" parses and "3.5" does not. For data files and web protocols pass CultureInfo.InvariantCulture:

VB
Imports System.Globalization

Dim price As Decimal
Decimal.TryParse("1234.50", NumberStyles.Number, CultureInfo.InvariantCulture, price)
C# Stand-in (C#): TryParse with a good and a bad input

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Casting objects: DirectCast, TryCast and TypeOf

When a variable's declared type is a base class or interface, you often need the real type. DirectCast converts a reference when you know the object's type, TryCast returns Nothing when it does not match, and TypeOf ... Is tests first:

VB
Dim animal As Animal = New Dog()

If TypeOf animal Is Dog Then
    Dim d As Dog = DirectCast(animal, Dog)
    d.Fetch()
End If

Dim cat As Cat = TryCast(animal, Cat)    ' Nothing: it is a Dog
If cat IsNot Nothing Then cat.Purr()

DirectCast is faster than CType for reference types and does not perform a user-defined conversion; it only succeeds if the object really is (or derives from) the target type. Unboxing a value from Object also requires the exact type: DirectCast(CObj(5), Long) fails because the box holds an Integer.

C# Stand-in (C#): type tests and safe casts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The Convert class and ToString

System.Convert offers ToInt32, ToDouble, ToString, ToBoolean, ToBase64String and more. Convert.ToInt32(Nothing) returns 0 rather than throwing, while CInt(Nothing) also yields 0. Every object has ToString(), and numbers accept format strings: n.ToString("N2"), n.ToString("X") for hexadecimal.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which conversion is narrowing?

    Double to Integer can lose the fraction (and overflow), so it needs an explicit conversion under Option Strict On.
  2. 2. What does CInt(2.5) return in VB.NET?

    CInt rounds half to even (banker's rounding), so 2.5 becomes 2 and 3.5 becomes 4.
  3. 3. Which approach handles bad user input without throwing an exception?

    TryParse returns False for invalid text and never throws for format problems.
  4. 4. What does TryCast return when the object is not of the requested type?

    TryCast is the non-throwing cast for reference types; check the result against Nothing.
  5. 5. What does Option Strict On forbid?

    It makes risky implicit conversions and run-time member lookup compile-time errors.

Summary

  • Widening conversions are automatic; narrowing ones need an explicit conversion with Option Strict On, which every project should enable.
  • CInt and friends convert (and round); CType, DirectCast and TryCast convert between reference types.
  • Parse user input with TryParse, and pass CultureInfo.InvariantCulture for machine-readable data.
  • TypeOf x Is T tests a type before you cast.

Next: Nullable Values and Dates