The difference in the declaration is: "var x = .." vs "var x; x = .."

I'm new to C #, please help me understand the difference between the description below:

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 expression as

class_a variable_name; 
variable_name = new class_a(); // this is working fine
+4
source share
5 answers

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

var variable_name = new class_a();

the compiler reports what new class_a()is an expression that gives an object of type class_a. Therefore, it is variable_namedeclared as a type class_a. This code is fully equivalent

class_a variable_name = new class_a();

, . , .

+7

var , .

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

, .

var i;        // no data type can be inferred
+5

var, datatype, , var 'variable' datatype.

var.

, .

+4

var , :

var var_name; // The compiler does not know what type var is. It has not been inferred. Error!

var var_name = new class_a(); // The compiler knows var has been inferred as class_a();

...

class_a var_name = new class_a();

ILSpy, , ILSpy , var.

+2
source
Compiler

wants to know the type of variable when allocating part of the memory for it. 3rd line does this and then gives it a value. the first line is fine, because the compiler knows in one line that the variable must be of type class_a, and it will allocate memory and at the same time give the value of the object new class_a()!
but the second gives you an error, because it will allocate memory without type! and you cannot put any object of any type in this particular memory!

0
source

Source: https://habr.com/ru/post/1536580/


All Articles