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
C# for beginners
C# for beginners

Are you learning C#? Try our test we designed to help you progress faster.

Test yourself