John P
John P

Reputation: 249

Why can't a value be assigned to a property in the class body except in its declaration?

I hope this question isn't too dumb - I wasn't able to find an answer, partly because I don't know how to phrase it well, but I think a small amount of code will explain it well:

class MyClass
{
    int value = 10;
}

What exactly does this do? Given that

class MyClass    
{
    int value;
    value = 10;
}

does not work (understandably- it doesn't make sense to assign a value to a member of a class, when we're not working with an actual instance, and this member is not static), so I would expect the former to not work either - but I suppose it might just be a short notation for "initialize this member to 10 when an instance is created", is that right?

Upvotes: 1

Views: 861

Answers (3)

Ortiga
Ortiga

Reputation: 8814

I'll try to give you a bit of a more "advanced" answer, while keeping in a simple terms.

An statement - such as an assignment to a field/variable - needs to be part of a method body.

The first example works because it's a C# compiler trick.

Under the hood, what it does is setting the value via a generated constructor method. To show this, I've decompiled the C# code of your class to IL, the intermediate language it compiles to.

(I know the code looks weird, but it's the under-the-hood language of the .net ecosystem)

MyClass..ctor: // ctor means constructor
IL_0000:  ldarg.0     
IL_0001:  ldc.i4.s    0A      // 0A is 10 in hexadecimal
IL_0003:  stfld       UserQuery+MyClass.bar
IL_0008:  ldarg.0     
IL_0009:  call        System.Object..ctor
IL_000E:  nop         
IL_000F:  ret 

Your second example does not work because it's not part of the body a method. The C# can't know when to run it.

You can change it to a constructor you create youself:

class MyClass
{
    int value;

    public MyClass()
    {
        value = 10;
    }
}

Upvotes: 1

marcelodmmenezes
marcelodmmenezes

Reputation: 221

This is called a field initializer. Like you said is just an inline shortcut to "initialize this member to 10 when an instance is created".

The initialization occurs before the constructor call.

Field initialization is defined by the language, so the compiler knows what to do. Statements in the body of the class, like the assignment value = 10 are not specified by the language, resulting in a compiler error. That's why the second approach doesn't work.

Upvotes: 2

K4R1
K4R1

Reputation: 885

Make it like this:

class MyClass
{
  MyClass(int value)
 {
  this.value = value; 
 }
}

Later when creating new instance:

MyClass classExample = new MyClass(3); // 3 is example value for int value.
// this would set the value to 3 for the "classExample"-instance of class "MyClass".

Alternatively setting default value:

    class MyClass
{
  MyClass()
 {
  value = 0; // default value would be 0 for all new instances of MyClass. 
 }
}

Upvotes: 0

Related Questions