-2

Why do I need copy constructor when I can copy one object to the another just by using the following C# statement?

objNew=objOld;
DandC
  • 33
  • 1
  • 2
    C# does not have copy constructors. – leppie Jan 06 '15 at 06:32
  • Maybe [this question](http://stackoverflow.com/questions/3345389/copy-constructor-versus-clone) answers your question? – SameOldNick Jan 06 '15 at 06:33
  • 2
    @leppie but you can write one. http://msdn.microsoft.com/en-us/library/ms173116.aspx – anurag-jain Jan 06 '15 at 06:36
  • @a4anurag: That is a very poor man's copy constructor ;p – leppie Jan 06 '15 at 06:37
  • 1
    This is what I hate about SO. A new person comes and we bombard him with downvotes and make him feel that his question is irrelevant. The OP might not bother coming back to SO after such a start. – anurag-jain Jan 06 '15 at 06:38
  • @a4anurag Perhaps if new people (1) actually searched before asking and (2) took the time to familiarize themselves with what constitutes a good question ([ask]), that wouldn't happen. Unfortunately for everybody, they rarely do. – dandan78 Jan 06 '15 at 07:18

2 Answers2

4

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
Leon
  • 919
  • 6
  • 21
0

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.

Write a Copy Constructor