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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With