0

I was just wondering why C# allows me to declare a variable using the var keyword inside a method

private SomeMethod()
{
    var someVariable = 5;
}

but not in global scope

Public partial class SomeClass
{
    var someVariable = 5;

    public SomeClass()
    {
    }
}

I've tried googling the question and I can't find any answers.

Ralt
  • 2,084
  • 1
  • 26
  • 38
  • 1
    In your second example, `someVariable` is a `field`. How do you think compiler can decide it's type? From Eric Lippert; [Why no var on fields?](http://blogs.msdn.com/b/ericlippert/archive/2009/01/26/why-no-var-on-fields.aspx) – Soner Gönül Nov 06 '14 at 15:06
  • Do you really can use it in method? Variables with var have to have defined type, so just var someVariable won't work. It have to be like this: var someVariable = 5; – Paweł Reszka Nov 06 '14 at 15:07
  • 6
    @SonerGönül: Actually, both examples are illegal, but that isn't the point of the question. – SLaks Nov 06 '14 at 15:07
  • [Right here](http://blogs.msdn.com/b/ericlippert/archive/2009/01/26/why-no-var-on-fields.aspx) – Jonesopolis Nov 06 '14 at 15:07
  • @SLaks Yes, you are right of course without they didn't assign any value :) – Soner Gönül Nov 06 '14 at 15:08

1 Answers1

1

Field initializers can have cyclic dependencies.

How should the following code compile?

class A { public var a = B.b; }
class B { public var b = A.a; }

Local variables cannot have cyclic initializers, so type inference is fine.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Last sentence is inaccurate, see http://ideone.com/IQ4e80 – Ben Voigt Nov 06 '14 at 15:11
  • @BenVoigt: I know. https://twitter.com/Schabse/status/530389303340179458 But for all practical purposes, it is correct. – SLaks Nov 06 '14 at 16:13
  • Shevdov's solution shouldn't compile, since it reads a variable which is not definitely assigned. I went to some trouble to ensure that the variable would only be written to. – Ben Voigt Nov 06 '14 at 16:19
  • @BenVoigt: Shvedov's solution only works because the struct has no fields, so you aren't actually reading anything. My original answer was `int x = x = 0;` – SLaks Nov 06 '14 at 16:24