0

I have a property defined as public bool? Enable{get; init} in a record. After the record is created, I broke into VS debugger and tried editing its value. It gives the following error when doing so:

CS8852: Init-only property or indexer can only be assigned in object initializer...

Isnt the debugger supposed to edit in memory ? Why is this not the case.

Frank Q.
  • 6,001
  • 11
  • 47
  • 62
  • What memory location? It's a property. It doesn't have a memory location, it has accessors. The debugger doesn't know how or make assumptions about how it's backed. It still has to call the `init` accessor, and can't. – madreflection Oct 19 '22 at 03:34
  • When you edit a value in debugger, the value is modified in memory (which is where the program is loaded and heap and registers are used). That is what I meant. – Frank Q. Oct 19 '22 at 17:33
  • 1
    I knew what you meant. I was pointing out that you're talking about something that doesn't exist. A property has accessors. It doesn't have an inherent memory location. Even auto-implemented properties technically don't have an inherent memory location. The debugger doesn't look for patterns and try to affect backing fields because that could have negative consequences. It must call the accessor. `init` accessors are just `set` accessors with metadata that prevents them from being used outside of compiler relaxation. The debugger doesn't attempt to employ that relaxation. – madreflection Oct 19 '22 at 17:44

1 Answers1

1

We can see the definition of init:

In C# 9 and later, the init keyword defines an accessor method in a property or indexer. An init-only setter assigns a value to the property or the indexer element only during object construction. This enforces immutability, so that once the object is initialized, it can't be changed again.

So it will report an error if try to modify its value when debugging.

This link can give more information. Hope it can help you.

Jingmiao Xu-MSFT
  • 2,076
  • 1
  • 3
  • 10