C# – Is VB’s Dim the same as C#’s var

cvb.net

This is a small doubt: On VB, I can declare variables using Dim. In C#, I can declare then using var. I'm more familiar with the intricacies of C#, and I know that var uses type inference to determine the type of the variable. But I'm not sure what 'Dim' does.

I've seem this question on SO, but it doesn't compare both keywords. If there's a difference, can someone tell me which?

Best Answer

That depends if Option Infer is specified. Normally, the following are equivalent:

'VB.Net
Dim myVar
Dim myString = "Hello world!"
Dim myString2 As String = "Hello world!"
//C#
object myVar;
object myString = "Hello world!"; //Notice type is object, *not* string!
string myString2 = "Hello world!";

However, with Option Infer enabled, Dim becomes more like var when the variable is initialized on the same line:

'VB.Net
Option Infer On
Dim myVar
Dim myString = "Hello!"
//C#
object myVar;
var myString = "Hello!"; //Or the equivalent:  string myString = "Hello!";

Note that this can lead to some confusion because suddenly initializing a variable at the point of declaration means something different from initializing it later:

'VB.Net
Option Infer On
Dim myVar1
myVar1 = 10
Dim myVar2 = 10

myVar1 = New MyClass() 'Legal
myVar2 = New MyClass() 'Illegal! - Value of type 'MyClass' cannot be converted to 'Integer'

This can be fixed by enabling Option Strict, which (among other things) forces all variables to be given a type (implicitly or not) at the time of declaration.