So the code below is perfectly valid and it outputs 5 as excpected and the type of foo
is inferred as System.Int32
.
class Program
{
static void Main()
{
var foo = 5;
Console.WriteLine(foo);
}
}
But if you write something like this
class Program
{
static var foo = 5;
static void Main()
{
Console.WriteLine(foo);
}
}
you get the following error:
The contextual keyword 'var' may only appear within a local variable declaration.
What is the problem of declaring variable using the var
-keyword at class level? I don't quite understand this, so can anybody make it clear?