0

Hello I would like to ask about this code:

Edit: The class is immutable, I make it auto-property instead of private.

public class Person {
    public int Id { get; }
    public string Name { get; }
    public string Title { get; }
    public int Age { get; }
    public Image Picture { get; }

    .... // lot of other fields

    private string Address { get; }

    public Person(int id, string name, ...) {
    // usual constructor init
    }
}

var John = new Person(1, "John", "Mr.", 54, ... );

Now I would like to create a new person (without mutation) based on John, only small modification on some fields, such as name and age.

In Javascript I could do something like this:

let bob = Object.assign({}, john, {name: "bob", age: 55};

How to return a new object with little modification in C#?

// something like this?
var Bob = Person.From(John, name: "Bob", age: 55);
Kevin Tanudjaja
  • 866
  • 1
  • 9
  • 16
  • Have a look at the examples and remarks here: https://learn.microsoft.com/en-us/dotnet/api/system.object.memberwiseclone?view=netframework-4.8 – thehennyy Aug 28 '19 at 09:42
  • https://stackoverflow.com/questions/78536/deep-cloning-objects Possible you want to know how to deep clone a object in C# – TimChang Aug 28 '19 at 09:44
  • 1
    I don't think the "duplicate" answer actually answers the question. OP doesn't want to clone the object, he wants to make a copy with one or two properties changed. After cloning the object, he's still left with the same problem - and it looks like this is an immutable class, so he can't just mutate the properties in the clone. – Matthew Watson Aug 28 '19 at 09:52
  • 1
    `Record` types have been proposed for C# (but they are still at the proposal stage). If/when they are implemented, you could write code like `var john = person with {name: "Bob", age: 55};` - but that's probably C#9 or later, if ever! – Matthew Watson Aug 28 '19 at 10:03
  • [This article about implementing "With" semantics in C#](https://www.productiverage.com/implementing-f-sharp-inspired-with-updates-for-immutable-classes-in-c-sharp) might be of interest. – Matthew Watson Aug 28 '19 at 10:13
  • oh very nice, I'm pretty sure that "with" will do exactly what I wanted, sadly that one is not implemented yet in c#, Shallow/ Deep Copy doesn't look like a solution, I still need to change some fields.. and field with reference type should not be shared between John and Bob – Kevin Tanudjaja Aug 28 '19 at 10:18
  • @KevinTanudjaja if you want a copy, but change name and age, if doing `bob.Title = "Sir";` should change `john.Title` too ? – Cid Aug 28 '19 at 10:35
  • @Cid , hello, John should be immutable type, John title should be "Mr" until he got garbage collected. – Kevin Tanudjaja Aug 28 '19 at 14:03

0 Answers0