C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Articles » .NET Framework »

Cloning in .NET


Posted Date: 22 Nov 2004    Resource Type: Articles    Category: .NET Framework
Author: Balamurali BalajiMember Level: Diamond    
Rating: 1 out of 5Points: 10



Introduction

The history of Cloning dates back to more than a century ago when scientists started digging the cells and exploring more on cell division. Lately, to our knowledge, in 1996, a sheep named “Dolly” was born, the first animal cloned from animal cells. “Dolly” was an exact replica of its parents and relatives in terms of genetic structure, DNA, blood cells etc.

Cloning in Object Oriented Designs

Almost contemporarily, in the world of computers, a new technology was being developed to demonstrate the real world objects and to create software that exactly (Not much attained, even today!) implements real world applications. That is, Object Oriented Software Development.

Very soon, Scientists innovated a new concept called “Patterns” that identifies re-usable components, classes, interfaces and relationships among them. They found three types of patterns namely, Creational, Structural and Behavioral patterns. Creational patterns deals with the creation of similar objects; Structural patterns deals with the layout and inner structure of classes and interfaces; Behavioral patterns deals with the relationships among the classes and interfaces.

Needless to say, .NET Framework is an infrastructure that incorporates patterns at a very higher level. Re-use of design patterns emulated the process of cloning in software development.

Cloning .Net

Cloning is used to make additional, identical copies or instances of an object. When you do cloning, you are actually getting a new object and a new reference variable to that object.

.NET Common Language Specification (CLS) supports two types of cloning viz. Shallow Clones and Deep Clones.

Shallow Clones allows you to make a copy of an object whereas Deep Clones allows you to make a copy of an object and also any references to the objects being maintained by the object.

A shallow copy creates a new instance of the same type as the original object. If the field is a value type, a bit-by-bit copy of the field is performed. If the field is a reference type, the reference is copied but the referred object is not; therefore, the reference in the original object and the reference in the clone point to the same object. In contrast, a deep copy of an object duplicates everything directly or indirectly referenced by the fields in the object.

MemberwiseClone method found in System. Object class is a shallow clone. It is a protected method which cannot be overridden but still can be used by the owner class and derived classes or using Me (VB.Net) / this (C#), the current instance of the class.

Your class should implements the Icloneable interface if a deep or shallow copy of the object needs to be publicly exposed to users.

Example:

class A {
public int age;
public string name;
}

class B: A{

static void Main() {
// Creates an instance of B and assign values to its fields.
B b1 = new B();
b1.age = 42;
b1.name = "Sam";

// Performs a shallow copy of b1 and assign it to b2.
B m2 = (B) b1.MemberwiseClone();
}
}

HashCodes

When talking about cloning of objects, a flashlight on the subject of Hash codes is inevitable. As you all know, hash code is an integer key, created on the contents of an object, which can be used as a means of searching and sorting objects.

Every object in .NET produces a hash code and those codes are stored in a Hash table. Objects like List of URLs, collection of IP addresses, Elements in an array, String of Characters are the few to name.

GetHashCode method is used to implement such hash tables and returns a hash code for the current object. The default implementation of GetHashCode does not guarantee uniqueness or consistency and it is not used as a unique object identifier for hashing purposes. Derived classes must override GetHashCode with an implementation that returns a unique hash code. For best results, the hash code must be based on the value of an instance field or property, instead of a static field or property.

Cloning of Strings

The method of String Class returns a value, which is not an independent copy of this instance; it is simply another view of the same data. It just returns a reference to the current instance of the string.
The implementation of GetHashCode provided by the String class returns unique hash codes for unique string values. Therefore, two String objects return the same hash code if they represent the same string value.

Look at this sample code:

Dim T1,T2 as String
Dim C1 as Object
T1 = “Welcome to Cloning”
C1 = T1.Clone()
T2 = C1.ToString()
Console.WriteLine(“{0}”, T2);

Here, you work with the new object C1 for copying purposes, instead of String.

Icloneable Interface

It is a system-defined interface that the classes implemented by this interface support cloning in a more ”deep copy" semantics. It has a single method: Clone.

namespace System
{
interface ICloneable
{
object Clone();
}
}

ICloneable interface is not that much simpler for the well-known reason. It's weakly-typed; it's specified to return an object of anything. You need to downcast the clone back to the type in question.

class A : ICloneable
{
object ICloneable.Clone()
{
// simply delegate to the type-safe method
return this.Clone();
}

Conclusion

Readers might ask one question:”why is there no "DeepClone" method on System.Object?”
.Net framework would’ve provided a method that queries each member for the ICloneable interface, or that calls ICloneable.Clone method on that member or performs a bitwise (shallow) copy of the member, for this purpose. But, readers might be exclaimed to know the fact that .Net runtime doesn’t seem to make use of Icloneable either, even though it is a well-known interface.



Responses

Author: praneetha     22 Apr 2005Member Level: Gold   Points : 0
looks like he copied everything from soem other website..and so sad that doesn't even give references...i think dotnetspider should chekc for references before publishing anything


Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
(No tags found.)

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Message Queuing – A boon to Enterprise Network
Previous Resource: Export Data to CSV ( Excel )
Return to Discussion Resource Index
Post New Resource
Category: .NET Framework


Post resources and earn money!
 
More Resources



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use