validation - How to create immutable objects in C#? -


in question best practices c# pattern validation, highest voted answer says:

i tend perform of validation in constructor. must because create immutable objects.

how create immutable object in c#? use readonly keyword?

how work if want validate in constructor of entity framework generated model class?

would below?

public partial readonly person {     public person() } 

the interesting question here question comments:

what kind of object have not need modify values @ point? i'm guessing not model class, correct? i've had change name of person in database - wouldn't fit idea.

well, consider things immutable. numbers immutable. once have number 12, it's 12. can't change it. if have variable contains 12, can change contents of variable 13, changing the variable, not the number 12.

same strings. "abc" "abc", , never changes. if have variable contains "abc", can change "abcd", doesn't change "abc", changes variable.

what list? {12, "abc"} list 12 followed "abc", , list never changes. list {12, "abcd"} different list.

and that's things go off rails. because in c# can either way. can there referential identity between 2 lists if lists allowed mutate contents without changing identity.

you hit nail right on head when talk "model". modeling changes? if so, possibly wise model type changes. benefit of characteristics of model match system being modeled. down side becomes tricky "rollback" functionality, "undo" change.

that is, if mutate {12, "abc"} {12, "abcd"} , want roll mutation, how do it? if list immutable keep around both values , choose 1 want "current" value. if list mutable have have undo logic keep around "undo function" knows how undo mutation.

as specific example, can create immutable database. how change name of in immutable database? don't. create new database has data want in it. trick immutable types efficiently, without copying billions of bytes. immutable data structure design requires finding clever ways share state between 2 nearly-identical structures.


Comments

Popular posts from this blog

linux - Mailx and Gmail nss config dir -

c# - Is it possible to remove an existing registration from Autofac container builder? -

php - Mysql PK and FK char(36) vs int(10) -