I’m trying to use the init setters on a regular record, and they don’t seem to work. But when I add the word "struct" to make it a record struct it works fine. Is this intended? It seems weird.
It doesn’t seem to be a visual glitch because the build fails because of it, and restarting visual studio makes no difference. Adding empty brackets also doesn’t help.
Error when using record’s init setters
>Solution :
I’m trying to use the init setters on a regular record, and they don’t seem to work.
You’re using a Primary Constructor syntax on your record, and as with any constructor, any time you use the new keyword to create an instance (as opposed to with syntax) you need to provide values to the constructor. The fact that you could then also initialize that value via initializer syntax is just an artifact of the fact that the primary constructor’s argument is also an init property.
But when I add the word "struct" to make it a record struct it works fine. Is this intended?
Yes. The reason that this changes when making your record a struct is that C# has different rules for structs in general. For example, structs always have a public default (no-argument) constructor, whereas adding an explicit constructor will remove the default constructor from classes. Also, structs don’t require any explicit initialization: if you never use the new keyword, they’ll just get initialized automatically using the default constructor.