Saturday, December 29, 2007

Implicit variable declaration in .NET 3.5

In C# 3 and Visual Basic 9, you can declare variables without having to specify the type of the variable. This isn't the same as the variant type in Visual Basic, but rather the compiler's ability to determine the type of the variable from the initialization value.

Here's how it works:
var i = 3; //C#
Dim i = 3 'VB

Using implicit declaration of variables requires you to specify a non-null value since a null only represents the generic object type.

EDIT: You can get the implicit declarations feature in LINQ projects (CTP) with Visual Studio 2005.

2 comments:

JV said...

You've greatly confused "type inference" with "implicit variable declaration." The type of the variable is being inferred from the type of what the right hand expression resolves to. This is greatly different from implicit variable declaration, where I might omit the "var" entirely and say "i = 0;" and the compiler says "Oh, there is no i as an identifier in the symbol table, I will take this as its declaration and create it for you." PHP is an example of a language that has implicit variable declaration, this is on top of dynamic typing, and therefore type inference. I recommend you change this post greatly as to avoid confusing people.

Unknown said...

JV you are mistaken. Per the MSDN reference this is in fact an example of implicit variable declaration.

http://msdn.microsoft.com/en-us/library/ms364047(VS.80).aspx

"When a local variable declaration specifies var as the type and no type named var is in scope, the declaration is an implicitly typed local variable declaration."