Created
November 25, 2013 12:00
-
-
Save JamesTryand/7640273 to your computer and use it in GitHub Desktop.
C# Immutable Builders
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Basically the important bit is near the bottom | |
| public class MyFancyImmutableObject { | |
| public string FirstValue { get; private set; } | |
| public string SecondValue { get; private set; } | |
| public string ThirdValue { get; private set; } | |
| public string FourthValue { get; private set; } | |
| public MyFancyImmutableObject(string firstValue, string secondValue, string thirdValue,string fourthValue){ | |
| FirstValue = firstValue; | |
| SecondValue = secondValue; | |
| ThirdValue = thirdValue; | |
| FourthValue = fourthValue; | |
| } | |
| public string SomethingAwesome(string wibble){ | |
| return wibble; // but really you'd be doing something here | |
| } | |
| public int SomethingEquallyAmazing(string woo){ | |
| return default(int); | |
| } | |
| public MyFancyImmutableObject KaPow(MyFancyImmutableObject anotherone){ | |
| return this; // blah blah you get where this is going for the immutable object malarky | |
| } | |
| } | |
| public class MyFancyImmutableObjectBuilder { | |
| internal string FirstValue = "sensibledefault1"; | |
| internal string SecondValue = "sensibledefault2"; | |
| internal string ThirdValue = "sensibledefault3"; | |
| internal string FourthValue = "sensibledefault4"; | |
| public MyFancyImmutableObjectBuilder WhereTheFirstValueIs(string firstValue) { | |
| FirstValue = firstValue; | |
| return this; | |
| } | |
| public MyFancyImmutableObjectBuilder WhereTheSecondValueIs(string secondValue) { | |
| SecondValue = secondValue; | |
| return this; | |
| } | |
| public MyFancyImmutableObjectBuilder WhereTheThirdValueIs(string thirdValue) { | |
| ThirdValue = thirdValue; | |
| return this; | |
| } | |
| public MyFancyImmutableObjectBuilder WhereTheFourthValueIs(string fourthValue) { | |
| FourthValue = fourthValue; | |
| return this; | |
| } | |
| public static implicit operator MyFancyImmutableObject(MyFancyImmutableObjectBuilder value) { | |
| return new MyFancyImmutableObject(value.FirstValue, value.SecondValue, value.ThirdValue, value.FourthValue); | |
| } | |
| } | |
| public class ExampleForMyFancyImmutableObject{ | |
| public void Go(){ | |
| MyFancyImmutableObject b = (MyFancyImmutableObject)(new MyFancyImmutableObjectBuilder(). | |
| WhereTheFirstValueIs("Hello"). | |
| WhereTheSecondValueIs(" "). | |
| WhereTheFourthValueIs("!"). | |
| WhereTheThirdValueIs("World")); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment