Copy constructor in C#

  • Thread starter Thread starter Jesper
  • Start date Start date
J

Jesper

Hi,

Does the concept "copy constructor" from c++ excist in
c#. What is the syntax.

best regards Jesper.
 
Jesper said:
Does the concept "copy constructor" from c++ excist in
c#. What is the syntax.

As I understand it, a copy constructor is just a constructor which
takes an instance of a class and copies all the fields into another one
- so yes, you can write that in C# using normal constructors etc.
However, I believe it's generally a better bet to use
Object.MemberwiseClone() as that will deal with some of the subtleties
such as always creating an instance of the correct type rather than
just some supertype whose constructor you specify.
 
No, C# does not have the concept of copy constructors. You can write
something that looks like a copy constructor, but it won't be called from
behind the scenes.

You can define overload conversion functions, which applies to some of the
scenarios in which you'd want a copy constructor.

--
Eric Gunnerson

Visit the C# product team at http://www.csharp.net
Eric's blog is at http://blogs.gotdotnet.com/ericgu/

This posting is provided "AS IS" with no warranties, and confers no rights.
 
The problem with using MemberwiseClone is that it only produces a shallow
copy. What Jesper probably wants is a deep copy implementation.

The only thing that I can think of is to implement your own Clone method
that implements ICloneable. You can then do what you want. The reason this
might be better than a copy constructor is because methods in the framework
may take a parameter of ICloneable which means that your class would
automatically be copied by the system.
 
Hi,
As I understand it, a copy constructor is just a constructor which
takes an instance of a class and copies all the fields into another one
- so yes, you can write that in C# using normal constructors etc.

I dare to say that your undestanding of copy constructors is not exactly
correct.
Copy constructor in C++ is a constructor, which take as a parameter
reference to the same class. Memberwise copy is the default copy in c++, so
copy constructors are used to provide mostly a deep copy. In c# deep copy
can be only provided by calling a method (even assignment operator is not
overloadable).
Ofcourse you always can declare a normal constructor in c# which takes
reference to the same class.
For C++ classes created in the heap and C# classes it will be almost the
same.
The big differnce is for C++ structures and classes created in the stack and
C# structures (since classes are always created in the heap)

To demonstrate this my first example is in c++. I'll use struct, but the
same goes for the classes

struct MyStruct
{
//...some members here
public MyStruct()
{
//members initillization
}
public MyStruct(MyStruct& s)
{
//Deep copy of the *s* members
}
}
Now somewhere in the code we can do the following

MyStruct firstStruct;

MyStruct secStruct = firstStruct;

This will call the copy constructor for secStruct (not the overloaded
assignment operator if we had one) and we will end up with deep copy of the
firstStruct

The copy constructor will be used as well in the cases when we have a struct
or class as a parameter passed by value

void Foo(MyStruct s)
{
}

When we call
Foo(firstStruct) ;

A new object will be created in the stack inside Foo's body and its copy
constructor will be called and the result s is going to be a deep copy of
fisrtStruct.

Now let see the C# example

struct MyStruct
{
//...some members here
public MyStruct(....)
{
//member initialization
}

public MyStruct(MyStruct s)
{
//Deep copy of the *s* members
}
}

Somewhere in the code

MyStruct firstStruct = new MyStruct(......);

MyStruct secStruct = firstStruct;

//This will make Memberwise copy of firstStruct even though we have defined
a constructor that looks like C++ copy constructor.

In order to have this constructor called we have to create the object like
this
MyStruct secStruct = new MyStruct(firstStruct);

This is the reason why those constructors have special name in C++.

So the answer of the original question is *No. C# doesn't have the
conception of copy constructors*

B\rgds
100
 
Hi Eric,
Eric Gunnerson said:
No, C# does not have the concept of copy constructors. You can write
something that looks like a copy constructor, but it won't be called from
behind the scenes. Exactly

You can define overload conversion functions, which applies to some of the
scenarios in which you'd want a copy constructor.

Not always. You cannot overload type cast operation, which has been already
predefined.
So, you cannot overload type cast operation for a class to its base class or
to itself. So it cannot be used in some of the common cases as to initilize
object with the object of the same class

B\rgds
100
 
100 said:
Hi,


I dare to say that your undestanding of copy constructors is not exactly
correct.
Copy constructor in C++ is a constructor, which take as a parameter
reference to the same class. Memberwise copy is the default copy in c++, so
copy constructors are used to provide mostly a deep copy.

That's certainly one reason to create a copy constructor. Another one, more
common I believe, is to avoid memory leaks. Take a (very simple) C++ class
which implements a string:

class String
{
private:
char *str;

public:
String(char *string) {
if (string == 0)
throw("null pointer");
str = strcpy(string);
}

String(String &other) { // copy constructor
free(str); // avoid the leak
str = strcpy(other.str);
}

// Note: this class also needs a destructor and assignment
// operator to avoid similar leaks
}

Note: I'm not claiming this is good C++, but it does illustrate the point.

The default, compiler-generated copy constructor for String would simply
copy the "str" attribute, resulting in a memory leak. The hand-coded copy
constructor frees the memory. If .NET weren't garbage-collected, memberwise
copy would have to be made far more complicated to avoid this sort of leak.
 
Jasper... The real point is that a copy constructor is essential to C++,
but not essential to C#.

Since C++ is deterministic, objects appear like rabbits everywhere. The
assignment operator may call the copy constructor in C++ for proper
behavoir at deallocation. This is essential in C++ to avoid having two
variables representing the same object, each resulting in a call to the
destructor when each variable goes out of scope. The assignment
operator does _not_ call a copy constructor in C#. C# is not
deterministic, so the assignment operator may simply assign two
variables to the same object in memory. The object in memory may be
reclaimed when the object is no longer reachable, so that the
"destructor" is only called once.

http://www.geocities.com/jeff_louie/OOP/oop5.htm

Chapter 5 "C++ and Java Gumption Traps"

4) The Assignment Operator Does Not Call the Copy Constructor

This one really confuses a lot of coders. In C# the assignment operator
simply assigns a reference variable to an existing object, to a new
object, or to null. After the assignment, the reference variable
contains a
reference to an object or to no object (is null). The assignment
operator
does not call the copy constructor to create a new object. It is quite
legal
in C# to have two reference variables that contain references to the
same
object. The two variables occupy different memory locations on the
stack, but contain values that point to the same memory address on the
heap. Both references would have to be released (e.g. the reference
variables go out of scope, be reassigned, set to null) before the object
can be reclaimed. As a result, the "destructor" will only be called
once.
The following code simply creates two references to the same object:

MyClass c1= new MyClass();
MyClass c2;
c2= c1; 
bool isSameReference= (c1 == c2);  // c1 and c2 contain references to
the same object on the heap
Console.WriteLine(isSameReference.ToString()); // output--> true
Be clear that if variable c1 contains the only reference to an object,
setting c1 to null or reassigning c1 to another object will make the
original object unreachable and eligible for garbage collection.

Regards,
Jeff
Does the concept "copy constructor" from c++ excist in
c#. What is the syntax.<
 
Back
Top