Okay,
Maybe this is by design of c# or maybe I am going about this the wrong way.
Please look at the code I have below. I made it where you can copy and paste it into a console app and run it to see what I am talking about.
using System;
namespace ConsoleTest
{
class Program
{
static void Main()
{
var o1 = new oObject
{
Name = "Before Method"
};
var o1b = new oObjectBad
{
Name = "Before Method"
};
Console.WriteLine("Object Bad 1 Before: " + o1b.Name);
oObjectBad o2b = GetNewObjectBad(o1b);
Console.WriteLine("Object Bad 1 After: " + o1b.Name);
Console.WriteLine("Object Bad 2 After: " + o2b.Name);
Console.WriteLine(string.Empty);
Console.WriteLine("Object 1 Before: " + o1.Name);
oObject o2 = GetNewObject(o1);
Console.WriteLine("Object 1 After: " + o1.Name);
Console.WriteLine("Object 2 After: " + o2.Name);
Console.ReadLine();
}
public static oObject GetNewObject(oObject o)
{
oObject newObject = new oObject(o);
newObject.Name = "Changed in Method";
return newObject;
}
public static oObjectBad GetNewObjectBad(oObjectBad o)
{
o.Name = "Changed in Method";
return o;
}
}
class oObject
{
public oObject()
{
}
public oObject(oObject o)
{
Name = o.Name;
}
public string Name { get; set; }
}
class oObjectBad
{
public string Name { get; set; }
}
}
Now, here is what I don't understand.
When I pass in an object to the method, and update the objects property "Name". It then updates the original object which is outside of the method.
The way around this was to create the other object (as shown in code) to make a clone of the object and then update the clone and then return the clone.
So the question is this: Is there an easier way to pass in an object and update the properties of that object so i can have something like this without it updating the original object.
using System;
namespace ConsoleTest
{
class Program
{
static void Main()
{
var o1 = new oObject
{
Name = "Before Method"
};
Console.WriteLine("Object 1 Before: " + o1.Name);
oObject o2 = GetNewObjectBad(o1);
Console.WriteLine("Object 1 After: " + o1.Name);
Console.WriteLine("Object 2 (New Object) After: " + o2.Name);
Console.ReadLine();
}
public static oObject GetNewObjectBad(oObject o)
{
o.Name = "Changed in Method";
return o;
}
}
class oObject
{
public string Name { get; set; }
}
}
If this is confusing let me know and I will see if I can explain better.
EDIT: The reason why I am doing this is I need to clone an object in the database and the cloned object will need to have a couple of properties changed. I will then be using the ID from the original object and the new object for other data processing.
Thanks!