2

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?

Spontifixus
  • 6,570
  • 9
  • 45
  • 63
Dimitri
  • 2,798
  • 7
  • 39
  • 59
  • 9
    take a look at this http://blogs.msdn.com/b/ericlippert/archive/2009/01/26/why-no-var-on-fields.aspx – Alessandro D'Andria Aug 16 '13 at 08:36
  • in short, because they can't. Definite duplicate I say. – Jodrell Aug 16 '13 at 08:44
  • Its like the general question, "why doesn't this thing do this thing that I want?" and the answer is, "because nobody made it do it yet." Followed by some detailed explanation of how difficult that it is. – Jodrell Aug 16 '13 at 08:50
  • So this site is running out of space or what ?? What if it is a duplicate why you care if questions are duplicate ?and i don't find it duplicate with question in reference but actually question referred is the answer for this question .Do not take advantages of privileges you got and please provide some answer also . – Suraj Singh Aug 16 '13 at 10:58

0 Answers0