Faced a problem: I need to initialize the base class with minimal code writing, because it can expand or change in the future and I don’t want to go into the constructor every time and change / add field assignments.

I think the code will better express my thought) I need it to be like this:

class Base { public Base(Base b) { this = b; // <--- Так не работет а очень хотелось бы } public int field1 { get; set; } public int field2 { get; set; } } class Child: Base { /// Конструктор потомка public Child(Base b, int field3) : base(b) { this.field3 = field3; } public int field3 { get; set; } } 

field2 you have to manually assign values ​​for field1 and field2 ? something like that:

 /// Конструктор потомка public Child(Base b, int field3) { this.field1 = b.field1; this.field2 = b.field2; this.field3 = field3; } 

Is there not a wordy and effective way to solve this problem?

You can of course apply the auto-chopper, but can there be a way to solve this problem in c # style without frills and reflections?

1 answer 1

Judging by the question:

How to initialize the fields of the base class simply passing it an object of its own type?

The task itself comes down to creating a complete copy of the object to the new instance. For this, it is not necessary to re-initialize each property of the new object. It is enough to copy the old object completely into the new memory area.

This can be done via iCloneable:

 class myClass : ICloneable { public String test; public myClass Clone() { return this.MemberwiseClone(); } } 

and in that case you just take and do:

 var newInstance = oldInstance.Clone(); 

This can be done through binary serialization and instantaneous serialization:

 public static T DeepClone<T>(T obj) { using (var ms = new MemoryStream()) { var formatter = new BinaryFormatter(); formatter.Serialize(ms, obj); ms.Position = 0; return (T) formatter.Deserialize(ms); } } 

using:

 var newInstance = DeepClone<myClass>(myClassOldInstance); 

can you alter any of these codes for yourself personally as your heart desires