Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does c# need "var" identifier? [duplicate]

Tags:

syntax

c#

scala

Possible Duplicate:
What's the point of the var keyword?

Why does c# need the "var" identifier for type inferred type variables?

I mean what is the problem with just leaving it off:

a = 1;
//vs
var a = 1;

Reading Programming in Scala:

"Type variable" syntax you cannot simply leave off the type - there would be no marker to start the definition anymore.

But what is the different between leaving it off in the a:Int or int a?

like image 376
Andriy Drozdyuk Avatar asked Dec 01 '22 08:12

Andriy Drozdyuk


2 Answers

At least one reason that comes to mind is that it forces the programmer to declare their intent to introduce a new variable, as opposed to assigning to an existing variable. This enables the compiler to detect numerous common coding errors.

like image 118
Marcelo Cantos Avatar answered Dec 02 '22 22:12

Marcelo Cantos


Consider this:

class Foo
{
    int a;

    void Bar()
    {
        var a = 1;
    }
}

Without the var keyword, the assignment would be to the class member a.

var introduces unambiguously a new local variable.

like image 45
Diego Mijelshon Avatar answered Dec 02 '22 21:12

Diego Mijelshon