In this short tutorial, you will learn the key points of C# variables.
Initializing Variable
The C# compiler requires that any variable be initialized with some starting value before you refer to that variable in an operation. So you can not do the following in C#:
class Program { static void Main(string[] args) { int i; Console.WriteLine($"i: {i}"); } }
It will get compile error:
error CS0165: Use of unassigned local variable 'i'
Type Inference
C# can use Type Inference
with keyword var
, the compiler “infers” what the type of the variable is by what the variable is initialized to.
static void Main(string[] args) { var str = "Hello World"; Console.WriteLine($"{str}"); }