immutability - C# Immutable & Mutable types without duplication -


given following implementation of mutable , immutable types, is there way avoid duplicate code (mainly duplicate properties)?

i'd work immutable type default unless mutable type required (e.g. when binding ui elements).

we're using .net framework 4.0, plan switching 4.5 soon.

public class person {     public string name { get; private set; }     public list<string> jobs { get; private set; } // change readonlylist<t>     public person() {}     public person(mutable m) {         name = m.name;     }     public class mutable : inotifypropertychanged {         public string name { get; set; }         public list<string> jobs { get; set; }         public mutable() {             jobs = new list<string>();         }         public mutable(person p) {             name = p.name;             jobs = new list<string>(p.jobs);         }         public event propertychangedeventhandler propertychanged;         protected void onpropertychanged(string propertyname) {             // todo: implement         }     } }  public class consumer {     public consumer() {         // can use object initializers :)         person.mutable m = new person.mutable {             name = "m. utable"         };         // consumers can happily mutate away....         m.name = "m. utated";         m.jobs.add("herper");         m.jobs.add("derper");          // core of our app deals "realio-trulio" immutable types.          // yey! have constructor arity of 1 opposed         // new person(firstname, lastname, email, address, im, phone)         person im = new person(m);     } } 

no, there's no easy way avoid duplicate code.

what you've implemented effectivly builder pattern. .net stringbuilder class follows same approach.

the support immutable types in c# bit lacking, , language specific features make easier. having create builder real pain, you've discovred. alternative have constructor takes values, tend end mother of constructors, makes code unreadable.


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -