I'm pretty confused about the cleanest way about mantaining immutability.
This is the simplest and most stupid I got so far, but I'm still wondering if isn't there a less verbose way to achieve this
class MyClass
{
public int Property1 { get; }
public string Property2 { get; }
public MyClass CopyWith(int? property1 = default, string property2 = default)
{
return new MyClass
{
Property1 = property1 ?? Property1,
Property2 = property2 ?? Property2
};
}
}
class Program
{
static void Main()
{
var myObj = new MyClass { Property1 = 123, Property2 = "123" };
var myModifiedObj = myObj.CopyWith(property2: "456");
}
}
An extension methods with generics would involve A LOT of reflection, but I'm still convince that I'm overthinking and maybe there's a simpler solution that I'm missing...