In C#, why can you declare a variable using code 'int x;' but you can't declare a variable using code 'var x;'?
Experience Level: Junior
Tags: C#
Answer
This is because there are two ways of how to declare a variable. You can either declare it explicitly by specifying its data type. This is what is done in code 'int x;' Or you can declare it implicitly using 'var' keyword. In such case the data type of the variable gets inferred from the value that is assigned to the variable. And because in the code 'var x;' there is no value assignment, it's an invali syntax. This cannot work because it would be impossible to find out up from what data type the variable x has.
Related C# job interview questions
What does the method consist of in C#?
C# JuniorWhat are method parameters in C#?
C# JuniorWhat is a breakpoint in C# good for?
C# JuniorHow many classes should be in one .cs file and why?
C# JuniorWhat is the 'class' keyword used for in C#?
C# Junior