Hacker News new | past | comments | ask | show | jobs | submit login

> C# has this:

This is only syntactic sugar to allow using object initializers to initialize specific member varabiles of a class instance instead of simply using a constructor and/or setting member variables in follow-up statements. It's hardly the feature OP was describing.




While mutation of init-only properties is sometimes done by e.g. serializers through private reflection or unsafe accessors, it otherwise can lead to unsound behavior if class implementation does not expect this. You cannot bypass this through normal language means.

Same applies to readonly instance fields.

Where does "syntax sugar" end and "true features" begin?


Anyway, trying to actually prevent a program from modifying its own memory is really hopeless, right? So any promises beyond “syntactic sugar” would be resting on a poor foundation, perhaps even dangerously misleading.


You can always mmap a memory range, place a struct there, then mprotect it. And on the language side you cannot overwrite readonly structs observed by readonly refs (aside from unsafe, which will trigger segfault in this case).

There are ways to do it. What matters is the user ergonomics, otherwise, by this logic, most higher-level languages would have even less of a claim to immutability, and yet somehow it's not an issue?

If there are exotic requirements - there are exotic tools for it. FWIW static readonlys are blocked from modification even through reflection and modifying their memory with unsafe is huge UB.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: