I have a dictionary from which I "copy" a object form like this:
public class MyClass
{
public string objectId;
public string name;
}
Dictionary<string, MyClass> dictionary = new Dictionary<string, MyClass>();
dictionary.Add("1234", new MyClass() { objectId = "1234", name = "Peter" });
dictionary.Add("2314", new MyClass() { objectId = "2314", name = "Tim" });
dictionary.Add("4321", new MyClass() { objectId = "4321", name = "Viggo" });
MyClass newObject = new MyClass();
newObject = dictionary["1234"];
newObject.name = "Tommy";
Now, what I want to accomplish is that the name only changes in the newObject and not in the dictionary... As it is now, any changes made to the newObject also changes inside the dictionary...
How do I separate them?
Hoping for help and thanks in advance :-)
-------- EDIT ---------
Ok tried to make a function like this:
public static object CopyObject(object obj)
{
Dictionary<string, object> copy = new Dictionary<string, object>();
foreach (var field in obj.GetType().GetFields())
{
if (!field.IsNotSerialized && field.GetValue(obj) != null)
{
// everything in here can be serialized!
if (field.FieldType == typeof(string))
{
copy.Add(field.Name, field.GetValue(obj).ToString());
}
else if (field.FieldType == typeof(bool))
{
copy.Add(field.Name, bool.Parse(field.GetValue(obj).ToString()));
}
else if (field.FieldType == typeof(int))
{
copy.Add(field.Name, (int)Convert.ToInt32(field.GetValue(obj)));
}
}
}
return copy;
}
And then tried to create the new MyClass object like this:
newObject = CopyObject(dictionary["1234"]) as MyClass;
It return empty... What am I doing wrong here?