public static void MisTakenImmutability() { MyImmutableType immutable = new MyImmutableType(); CancellationTokenSource tokenSource = new CancellationTokenSource(); Task task1 = new Task(() => { while (true) { double circ = 2 * immutable.refData.PI * immutable.circleSize; Console.WriteLine("Circumference: {0}", circ); if (circ == 4) { Console.WriteLine("mutation detected"); break; } tokenSource.Token.WaitHandle.WaitOne(250); } }, tokenSource.Token); task1.Start(); Task.Delay(1000); immutable.refData.PI = 2; task1.Wait(); EndofProgram(); }
public void TestReadOnlyAutoProp() { MyImmutableType myImmutableType = new MyImmutableType(88m, DateTime.UtcNow); string display = myImmutableType.ToString(); System.Diagnostics.Debug.WriteLine(display); // myImmutableType.AmountDeposit = 80000m; // Get this error: Property or indexer 'property' cannot be assigned to — it is read only }
public void CanDumpImmutableObject() { // Arrange var input = new MyImmutableType("John Doe", 20); // Act var actual = input.Dump(); // Assert actual.Should().Be( @"{ ""Name"": ""John Doe"" [System.String], ""Age"": 20 [System.Int32] } [CrossCutting.Utilities.ObjectDumper.Tests.Helpers.MyImmutableType]"); }
static void Main47(string[] args) { // create a new instance of the immutable type MyImmutableType immutable = new MyImmutableType(); // create a cancellation token source CancellationTokenSource tokenSource = new CancellationTokenSource(); // create a task that will calculate the circumference // of a 1 unit circle and check the result Task task1 = new Task(() => { while (true) { // perform the calculation double circ = 2 * immutable.refData.PI * immutable.circleSize; Console.WriteLine("Circumference: {0}", circ); // check for the mutation if (circ == 4) { // the mutation has occurred - break // out of the loop Console.WriteLine("Mutation detected"); break; } // sleep for a moment tokenSource.Token.WaitHandle.WaitOne(250); } }, tokenSource.Token); // start the task task1.Start(); // wait to let the task start work Thread.Sleep(1000); // perform the mutation immutable.refData.PI = 2; // join the task task1.Wait(); // wait for input before exiting Console.WriteLine("Press enter to finish"); Console.ReadLine(); }
public static void Main(){ MyImmutableType mit = new MyImmutableType("An immutable type's state cannot be changed.", 49); Console.WriteLine(mit); }