Skip to content

Instantly share code, notes, and snippets.

@mishrsud
Created November 19, 2020 04:42
Show Gist options
  • Save mishrsud/e1198d6b02e639c34a7f61b729804f00 to your computer and use it in GitHub Desktop.
Save mishrsud/e1198d6b02e639c34a7f61b729804f00 to your computer and use it in GitHub Desktop.
void Main()
{
// 1: NOT QUITE IMMUTABLE
var mutablePerson = new MutablePerson();
mutablePerson.Name = "Clint";
mutablePerson.Age = 41;
mutablePerson.Dump("Initial Values");
mutablePerson.Name = "Jerry";
mutablePerson.Age = 32;
mutablePerson.Dump("After change");
// 2: GOTTA BE IMMUTABLE!!
// COMPILATION ERROR - MUST INITIALISE USING PARAMETERISED CONSTRUCTOR
// var immutablePerson = new ImmutablePerson();
var immutablePerson = new ImmutablePerson("Jane", 28);
immutablePerson.Dump("Immutable Shorthand");
// COMPILATION ERROR - INIT ONLY PROPERTY CANNOT BE SET IN THIS CONTEXT
// immutablePerson.Name = "Shiela";
// 3: IMMUTABLE TOO
// THIS IS OK - USE WHEN YOU NEED OBJECT INITIALIZER SYNTAX
var immutableV2 = new ImmutablePersonV2()
{
Name = "test",
Age = 17
};
// COMPILATION ERROR - CANNOT ASSIGN INIT ONLY PROPERTY HERE
//immutableV2.Name = "Change";
immutableV2.Dump("Immutable object initializer syntax");
// 4: CLONE AN IMMUTABLE, WITH CHANGES
var iMaClone = immutableV2 with { Age = 22 };
iMaClone.Dump("The Clone");
}
// You can define other methods, fields, classes and namespaces here
public record MutablePerson
{
// Get and Set can be dropped without altering the behaviour
public string Name { get; set; }
public int Age { get; set; }
}
public record ImmutablePerson(string Name, int Age);
public record ImmutablePersonV2
{
public string Name { get; init; }
public int Age { get; init; }
}
/*
Error CS8852 Init-only property or indexer ‘{your property}’ can only be assigned in an object initializer, or on ‘this’ or ‘base’ in an instance constructor or an ‘init’ accessor.
*/
/*
REFERENCES
- Record Types: https://dotnetcoretutorials.com/2020/09/25/record-types-in-c-9/
- Using Immutable Options: https://anthonygiretti.com/2020/08/19/asp-net-core-5-make-your-options-immutable/
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment