-1

I have an class that I fill from database:

 // original data
var dbData = this.GetOriginalData(ID);

Then I want to create a new instance of the same object in which I can modify properties but keeping the original one as it is.

If I do:

var newData = dbData;
newData.Text = "Sample";

Then dbData.Text is also being altered.

How can I create an instance of dbData without creating a new class and passing property by property or without using AutoMapper for example.

VAAA
  • 14,531
  • 28
  • 130
  • 253
  • 2
    may be relevant https://stackoverflow.com/questions/78536/deep-cloning-objects – Gianlucca Sep 11 '19 at 15:09
  • 3
    Possible duplicate of [Deep cloning objects](https://stackoverflow.com/questions/78536/deep-cloning-objects) – pix Sep 11 '19 at 15:11

1 Answers1

0

You can use the Json serializer to clone an object by creating a new object and copying all the properties using serialize/deserialize

public static T CloneJson<T>(this T source)
{            
    // Don't serialize a null object, simply return the default for that object
    if (Object.ReferenceEquals(source, null))
    {
        return default(T);
    }

    // initialize inner objects individually
    // for example in default constructor some list property initialized with some values,
    // but in 'source' these items are cleaned -
    // without ObjectCreationHandling.Replace default constructor values will be added to result
    var deserializeSettings = new JsonSerializerSettings {ObjectCreationHandling = ObjectCreationHandling.Replace};

    return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(source), deserializeSettings);
}
Jon
  • 3,230
  • 1
  • 16
  • 28
  • Thanks Jon how would you call the function? – VAAA Sep 11 '19 at 15:15
  • var newData = CloneJson(dbData); Where MyDataType is the class name of dbData – Jon Sep 11 '19 at 15:17
  • You'll also need to install Newtonsoft.Json from the Nuget Package Manager (right click your project, Manage Nuget Packages, search for NewtonSoft Json) – Jon Sep 11 '19 at 15:18