Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference in declaration: "var x = .." vs "var x; x = .."

Tags:

variables

c#

I am new to C#, please help me to understand the difference between the below statement:

var variable_name = new class_a(); // there is no error and is working fine

var variable_name; 
variable_name = new class_a(); // this line is throwing error

when I rewrote the statement as

class_a variable_name; 
variable_name = new class_a(); // this is working fine
like image 474
Abhishek Avatar asked Dec 01 '22 16:12

Abhishek


2 Answers

var is used to introduce an implicitly typed local variable. The type is known at compile time and is inferred from the type of the expression on the right hand side of the initialization statement. Using your example:

var variable_name = new class_a();

the compiler infers that new class_a() is an expression that yields an object of type class_a. Hence variable_name is declared as being of type class_a. This code is completely equivalent to

class_a variable_name = new class_a();

If the right hand side of the initialization is omitted, then there is no way for the compiler to infer the type. Hence the compilation error.

like image 66
David Heffernan Avatar answered Dec 10 '22 15:12

David Heffernan


var automatically infers the data type based on the value that the variable is initialized with.

var i = 3;    // 3 is an int; thus, i is declared as an int.

In your second example, there is no value specified, thus, inference is not possible.

var i;        // no data type can be inferred
like image 44
Heinzi Avatar answered Dec 10 '22 15:12

Heinzi