.net - C# and immutability and readonly fields... a lie? -
.net - C# and immutability and readonly fields... a lie? -
i have found people claim using readonly fields in class not create class's instance immutable because there "ways" alter readonly field values after initialization (construction).
how? ways?
so question when can have "real" immutable object in c#, can safely utilize in threading?
also anonymous types create immutable objects? , linq uses immutable objecst internally. how exactly?
you've asked 5 questions in there. i'll reply first one:
having readonly fields in class not create class's instance immutable because there "ways" alter readonly field values after construction. how?
is possible alter readonly field after construction?
yes, if sufficiently trusted break rules of read-only-ness.
how work?
every bit of user memory in process mutable. conventions readonly fields might create bits appear immutable, if seek hard enough, can mutate them. example, can take immutable object instance, obtain address, , alter raw bits directly. doing might require great deal of cleverness , knowledge of internal implementation details of memory manager, somehow memory manager manages mutate memory, can if seek hard enough. can utilize "private reflection" break various parts of safety scheme if sufficiently trusted.
by definition, fully trusted code allowed break rules of safety system. that's "fully trusted" means. if trusted code chooses utilize tools private reflection or unsafe code break memory safety rules, trusted code allowed that.
please don't. doing unsafe , confusing. memory safety scheme designed create easier reason correctness of code; deliberately violating rules bad idea.
so, "readonly" lie? well, suppose told if obeys rules, gets 1 piece of cake. cake lie? claim not claim "you piece of cake". that's claim if obeys rules, you'll piece of cake. if cheats , takes slice, no cake you.
is readonly field of class readonly? yes only if obeys rules. so, readonly fields not "a lie". contract is, if obeys rules of scheme field observed readonly. if breaks rules, maybe isn't. doesn't create statement "if obeys rules, field readonly" lie!
a question did not ask, perhaps should have, whether "readonly" on fields of struct "lie" well. see does using public readonly fields immutable structs work? thoughts on question. readonly fields on struct much more of lie readonly fields on class.
as rest of questions -- think you'll improve results if inquire 1 question per question, rather 5 questions per question.
c# .net immutability readonly
Comments
Post a Comment