Why do I need copy constructor when I can copy one object to the another just by using the following C# statement?
objNew=objOld;
Why do I need copy constructor when I can copy one object to the another just by using the following C# statement?
objNew=objOld;
You don't "copy" the object with objNew = objOld
. You create a reference, not a copy; see this
Parent a = new Parent() { ID = 1, Name = "A" };
Parent b = a;
b.ID = 2;
Console.WriteLine(a.ID); // output is 2
Whereas Parent being some object with ID and name. If you see output written = 2, why ? because a = b therefor: a.ID = 2 ( and not 1 what you expected with your "copy" > it's the same object with a different name ).
See Value vs Reference types (general programming) for instance this article; http://www.albahari.com/valuevsreftypes.aspx
What you want (or expect) is more down the line of this:
Parent a = new Parent() { ID = 1, Name = "A" };
Parent b = a.Clone(); // or copy or whatever you want to call it
b.ID = 2;
Console.WriteLine(a.ID); // here we have 1 now
Why do I need copy constructor when I can copy one object to the another just by using the following C# statement?
C# does not provide a copy constructor by default.
A copy constructor means a constructor which copies data of one object into another object.
That means if you want to manipulate your data during copying a object you need to define a copy constructor.