C# 3.0 Type Inference

One of the new language features of the C# 3.0 language release is type inference. Wikipedia has an excellent discussion on type inference, including a non-technical and technical explanation.

C# 3.0 introduces the concept of type inference with the var keyword. At first glance, this looks a lot like the old Variant keyword of Visual Basic. It isn't!

One of the compelling features of C# is that it is a strongly typed language whose variables are statically typed. The var keyword doesn't change this; it simply lets the compiler infer the variables data type from its context. To help clear this mystery up, lets look at an example:

In C# 2.0, you can write:

int i;
i = 1;

or simply:

int i = 1;

In C# 3.0, you can also write this as:

var i = 1;

What this actually means to the compiler is that the variable i is of the same data type as it's initializer. In this case, i would end up being compiled as an int. The key here is that i is still strongly typed. The other thing to realize is that the var keyword is only valid within the body of a method. You can't use it define class-wide variables that have an inferred type.

The var keyword was added to support anonymous types, another new feature in C# 3.0. Without this keyword, you wouldn't be able to create a variable of an anonymous type if you always needed to specify the type. An interesting side-effect of the var keyword is that you no longer have to specify the type name twice when you declare a variable.

List list = new List();

var list = new List();

The most important things to remember are:

  1. var != object != Variant
  2. You can only use the var keyword inside a method body.
This article is part of the GWB Archives. Original Author: Scott Dorman

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.