Implicit typing
Local variables can be declared without giving an explicit type. The var
keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement. The inferred type may be a built-in type, an anonymous type, a user-defined type, or a type defined in the .NET class library. For more information about how to initialize arrays with var
, see Implicitly Typed Arrays.
The following examples show various ways in which local variables can be declared with var
:
var
vs other types
var
vs other typesIf we declare a variable var
without initializing it we will have an error because the compiler will not allow us to. Also, if we assign a null value to var
variable, we will also have an error too.
Last updated