简体   繁体   中英

C# Why can't you change the variable value in the class scope?

I'm confused as to why C# doesn't let you change the variable value in the class scope after defining it.

Consider the code(This will not work):

class Foo
{
   private int x;
   x = 0;
}

Obviously you can do something like

class Foo
{
   private int x = 0;
}

or this

class Foo
{
    private int x;
    public void Bar()
    {
        x = 5;
    }
}

But I don't understand why the first way doesn't work as I thought as long as the variable is within the same scope you can modify it?

x=0; can only be part of a method. In case of private int x = 0; compiler will actually split that and put assignment into a constructor so you would have compiled version of

class Foo
{
    private int x;
    public Foo()
    {
        x = 0;
    }
}

Because this area

class Foo{ ... here ... }

designed for declaration of class. So it contais members with its default initialization and functions. You want to put functional code this is not allowed.

If you need to put construction code use constructors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM