Reputation:
In C++
, we have Copy Constructor, Destructors, overloaded = which are together called copy control.
My questions are:
Is copy constructor
used in C#
for initializing objects when passed to a function as argument
or when initializing
(not assigning) or when returning
an object from a function
as in C++
?
Does an implicitly overloaded =
operator function gets called when we assign (not initialize) any object to another object of the same type?
Upvotes: 3
Views: 471
Reputation: 67447
C# has no concept of a copy constructor, nor of overloading operator=
. In C# objects just exist and you use handles to them in your code. Handles can be copied "by value" to be used throughout your code, but that's a so-called "shallow" copy, the object itself is still the same, they all point to the same memory (indirectly).
Copy constructors are akin to deep copying in the managed world, and you can achieve that through ICloneable
, but it's completely manual and up to the object's implementation to write it. You can also achieve it through serialization (the boost
way) or through any manner of indirect ways.
As a final point, since object lifetimes are non-deterministic (they die when the GC arbitrarily decides they should die), there's no such thing as destructors either. The closest thing are finalizers (called non-deterministically when your object gets collected) and the IDisposable
pattern (along with using
) which give you a semblance of control over finalization. Needless to say they are rarely used.
Edit: I should point out that, while copy constructors have no equivalent, you do have "type casting" constructors through implicit
, the precise name escapes me at the moment.
Upvotes: 1
Reputation: 4206
No. If you want to provide copying mechanism, you do this by implementing the ICloneable interface: http://msdn.microsoft.com/en-us/library/system.icloneable.aspx
Upvotes: 1
Reputation: 726919
In fairness to C#, none of the intricacies of the C++ copy control are necessary because of the underlying garbage-collected memory model. For example, you do not need to control the ownership of dynamically allocated objects when copying objects, because you are free to have as many references to dynamic objects as you wish.
Upvotes: 1
Reputation: 203838
In C# you cannot overload the assignment operator.
Destructors don't really make sense in a managed memory world (most of the time). There is actually an equivalent (finalizers) but you should very rarely need to utilize them.
Copy constructors are made for certain classes, but it's not done nearly as often as in C++. It will never be called implicitly by the language, it will only be used when you manually call it.
Upvotes: 1