Skip to content

Instantly share code, notes, and snippets.

@Fagro
Created September 25, 2018 18:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fagro/cdaf8fe0c285021d7bf13c2ee1dbf98f to your computer and use it in GitHub Desktop.
Save Fagro/cdaf8fe0c285021d7bf13c2ee1dbf98f to your computer and use it in GitHub Desktop.
Immutable classes C#
extracted from : https://stackoverflow.com/questions/38575646/general-purpose-immutable-classes-in-c-sharp
class Program
{
static void Main(string[] args)
{
var immutable1 = new A(3, 4, new Batida(name: "juan", lastname: "Doe"));
var immutable2 = immutable1.With( Batida: new Batida("Roger", "Tan"));
Console.WriteLine($"data in inmutable 2 ({immutable2.X} and {immutable2.Y}) - Batida {immutable2.Batida.Name}");
Console.WriteLine($"data in inmutable 1 ({immutable1.X} and {immutable1.Y}) - Batida {immutable1.Batida.Name}");
Console.ReadLine();
}
}
public class Batida
{
public readonly string Name;
public readonly string Lastname;
public Batida(string name, string lastname)
{
Name = name;
Lastname = name;
}
}
public sealed class A
{
public readonly int X;
public readonly int Y;
public readonly Batida Batida;
public A(int x, int y, Batida batida)
{
X = x;
Y = y;
Batida = batida;
}
public A With(int? X = null, int? Y = null, Batida Batida = null) =>
new A(
X ?? this.X,
Y ?? this.Y,
Batida ?? this.Batida
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment