Deborah's Developer MindScape






         Tips and Techniques for Web and .NET developers.

July 28, 2009

Inferred Typing

Filed under: C#,LINQ,VB.NET @ 2:01 pm

If you are using Visual Studio 2008 (.NET Framework 3.5) or newer, you can leverage inferred typing. Inferred typing allows the compiler to infer your data types instead of you having to explicitly define the type. Variables that use inferred typing are still strongly typed, they just depend on .NET for determining (or inferring) the type.

Inferred typing is sometimes referred to as “duck typing”. This is from the truth that if something looks like a duck and quacks like a duck, it must be a duck. For more general information on inferred typing (or type inference), see this.

The compiler infers your data type based on its context. Here are some examples.

In C#:

var i = 1;

var x = "Hello";

var arr = new int[] {1, 2, 3, 4};

var c = new Customer();

var y = null; // Generates an error

To use inferred typing in C#, use the var keyword as in the above examples. Note that var is not short for variant and does not imply that the variables are weakly typed. Rather, the var keyword defines that the compiler should infer the type based on the context.

In VB:

Dim i = 1

Dim x = "Hello"

Dim arr() = New Integer() {1, 2, 3, 4}

Dim c = new Customer()

Dim y = Nothing

To use inferred typing in VB, you need to set Option Infer On:

  1. Double-Click on My Project under Solution Explorer.
  2. Click the Compile tab.
  3. Set Option Infer On.

If Option Infer is On, simply Dim the variable to take advantage of inferred typing. This does not imply that the variables are weakly typed or are of type Object. Rather, using Dim without a data type when Option Infer is On defines that the compiler should infer the type based on the context.

In the first example under either language, the inferred type of i is integer because it is assigned to 1. In the second example, x is inferred to be of type string. The arr variable is inferred to be of an integer array type.

The fourth example infers the type of c to be Customer and creates a new instance of the Customer class. This is less necessary as a shortcut in VB where you can also do this:

Dim c as New Customer

In the last example, VB infers the type of y to be Object. C# won’t attempt to infer the type and instead generates a compile error.

You can view the type that is inferred by hovering over the value in the Visual Studio text editor. In VB, hover over the variable. In C#, hover over the var keyword.

BUT – is this a good idea? Should you be leaving it up to the compiler to define your types?

The recommended best practice regarding inferred typing is as follows:

  • Do NOT use inferred typing for variables of intrinsic types (like in the above integer and string examples).
  • DO use inferred typing when creating a new instance, such as in the new Customer example.
  • DO use inferred typing when dealing with anonymous types (see this or this).
  • DO use inferred typing when working with LINQ and Lambda expressions.

Though a quick Bing of this topic shows that not all developers agree with these guidelines.

A common use of inferred typing is with LINQ and Lambda expressions because the data types of these expressions are often long and tedious.

For example:

In C#:

List<int> myList = new List<int>() { 1, 6, 8, 3, 2, 4, 15 };

var result = from item in myList
               where item < 5
               select item;

In VB:

Dim myArr() As Integer = {1, 6, 8, 3, 2, 4, 15}
Dim myList As List(Of Integer) = myArr.ToList

Dim result = From item In myList _
                Where item < 5 _
                Select item

NOTE: VB does not support List initializers but it does support array initializers. So to simplify the amount of code, an array initializer was used and then the array was converted to a List.

In both cases, the result variable type is System.Collections.Generic.IEnumerable<int>. Yuck!

Enjoy!

EDIT: 8/26/12

Two things to add to this:

1) VB does now support List initializers as of VB 10 (VS 2010).

2) In practice over the past few years, I have found that I also ignore the first recommendation for inferred typing. Why include the name of the type (string or int) when it is so obvious that you are assigning to a string or an integer?

2 Comments

  1.   Yann — August 13, 2009 @ 1:42 am    Reply

    Hi Deborah,

    I actually don’t agree with “Do NOT use inferred typing for variables of intrinsic types (like in the above integer and string examples)”.

    I use this a lot:

    dim title = “This is my title”

    I see no point in having to use:

    dim title as string = “This is my title”

    Am I missing some obscure reasoning here?

    Thanks,

    Yann

    PS – I think you need to change “Questions? Contact Susan at Susan-at-msmvps.com” that’s at the bottom of the page, lol.

  2.   DeborahK — August 13, 2009 @ 4:42 pm    Reply

    Hi Yann,

    Thank you for visiting my blog and for bringing up this topic.

    The main reason not to use inferred typing in this case is readability. Read more about this here:

    http://srtsolutions.com/blogs/billwagner/archive/2005/09/23/on-var-and-c.aspx

    And regarding your PS, Susan’s name at the bottom is correct. She is the one that manages this blogging site for all of the mvps.

    Thanks again!

RSS feed for comments on this post. TrackBack URI

Leave a comment

© 2020 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs