Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# Init setters don't work on class records

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading