Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is VB's Dim the same as C#'s var?

Tags:

c#

vb.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?

like image 760
Bruno Brant Avatar asked Apr 15 '11 15:04

Bruno Brant


2 Answers

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.

like image 116
BlueRaja - Danny Pflughoeft Avatar answered Oct 19 '22 01:10

BlueRaja - Danny Pflughoeft


They are not the same. Dim in VB simply means that what follows is a variable declaration.

For example, these two are equivalent:

Dim x As String = "foo"
string x = "foo"

In C#, var means that a variable declaration’s type is inferred by the compiler based on usage (initialisation). The same can be achieved in VB by simply omitting the type of the declaration. However, this also requires that Option Strict and Option Infer are activated:

Dim x = "bar" ' Compiler infers type of x = string
var x = "bar" // same here.
like image 38
Konrad Rudolph Avatar answered Oct 19 '22 01:10

Konrad Rudolph