Cloning C# objects is one of those things that appears easy but is actually quite complicated with many "gotchas." This article describes the most common ways to clone a C# object.

Shallow vs. Deep Cloning

There are two types of object cloning: shallow and deep. A shallow clone copies the references but not the referenced objects. A deep clone copies the referenced objects as well.

Hence, a reference in the original object and the same reference in a shallow-cloned object both point to the same object. Whereas a deep-cloned object contains a copy of everything directly or indirectly referenced by the object. See wikipedia for a detailed explanation.

Object Clone

ICloneable Interface

The ICloneable interface contains a single Clone method, which is used to create a copy of the current object.

public interface ICloneable
{
object Clone();
}

The problem with ICloneable is that the Clone method does not explicitly specify whether it is performing a shallow or deep copy, so callers can never be sure. Hence, there is some discussion about making ICloneable obsolete in the .NET Framework. The MSDN documentation seems to hint that Clone should perform a deep copy, but it is never explicitly stated:

The ICloneable interface contains one member, Clone, which is intended to support cloning beyond that supplied by MemberWiseClone… The MemberwiseClone method creates a shallow copy…

Type-Safe Clone

Another disadvantage of ICloneable is that the Clone method returns an object, hence every Clone call requires a cast:

Person joe = new Person();
joe.Name = "Joe Smith";
Person joeClone = (Person)joe.Clone();

One way to avoid the cast is to provide your own type-safe Clone method. Note that you must still provide the ICloneable.Clone method to satisfy the ICloneable interface:

public class Person : ICloneable
{
public string Name;
object ICloneable.Clone()
{
return this.Clone();
}
public Person Clone()
{
return (Person)this.MemberwiseClone();
}
}

Clone Options

Following are some of the more common approaches to clone a C# object:

1. Clone Manually

One way to guarantee that an object will be cloned exactly how you want it is to manually clone every field in the object. The disadvantage to this method is it's tedious and error prone: if you add or change a field in the class, chances are you will forget to update the Clone method. Note that care must be taken to avoid an infinite loop when cloning referenced objects that may refer back to the original object. Here is a simple example that performs a deep copy:

public class Person : ICloneable
{
public string Name;
public Person Spouse;
public object Clone()
{
Person p = new Person();
p.Name = this.Name;
if (this.Spouse != null)
p.Spouse = (Person)this.Spouse.Clone();
return p;
}
}

2. Clone with MemberwiseClone

MemberwiseClone is a protected method in the Object class that creates a shallow copy by creating a new object, and then copying the nonstatic fields of the current object to the new object. For value-type fields, this performs a bit-by-bit copy. For reference-type fields, the reference is copied but the referred object is not; therefore, the original object and its clone refer to the same object. Note this works for all derived classes, and hence you only need to define the Clone method once in the base class. Here is a simple example:

public class Person : ICloneable
{
public string Name;
public Person Spouse;
public object Clone()
{
return this.MemberwiseClone();
}
}

3. Clone with Reflection

Cloning by Reflection uses Activator.CreateInstance to create a new object of the same type, then performs a shallow copy of each field using Reflection. The advantage of this method is it's automated and does not need to be adjusted when members are added or removed from the object. Also, it can be written to provide a deep copy. The disadvantage is it uses Reflection, which is slower and not allowed in partial trust environments. Sample code

4. Clone with Serialization

One of the easiest ways to clone an object is to serialize it and immediately deserialize it into a new object. Like the Reflection approach, the Serialization approach is automated and does not need to be adjusted when members are added or removed from the object. The disadvantage is that serialization can be slower than other methods including Reflection, and all cloned and referenced objects must be marked Serializable. Also, depending on what type of serialization you use (XML, Soap, Binary), private members may not be cloned as desired. Sample code here and here and here.

5. Clone with IL

A fringe solution is to use IL (Intermediate Language) to clone objects. This approach creates a DynamicMethod, gets the ILGenerator, emits code in the method, compiles it to a delegate, and executes the delegate. The delegate is cached so that the IL is generated only the first time and not for each subsequent cloning. Although this approach is faster than Reflection, it is difficult to understand and maintain. Sample code

6. Clone with Extension Methods

Havard Stranden created a custom cloning framework using extension methods. The framework creates a deep copy of an object and all referenced objects, no matter how complex the object graph is. The disadvantage is this is a custom framework with no source code (Update: source code now included, see comment below), and it cannot copy objects created from private classes without parameterless constructors. Another problem, which is common to all automated deep copy methods, is that deep copying often requires intelligence to handle special cases (such as unmanaged resources) that cannot be easily automated.

16

View comments

  1. Simply Great stuff, Short and Precise

    ReplyDelete
  2. Great article, thanks. BTW, I think your "Clone Manually" example will lead to an infinite recursion, if P1 and P2 are spouses: P1.clone -> P2.clone -> P1.clone -> ...

    ReplyDelete
  3. Thanks for this overview. Great introduction into this subject. A time saver.

    ReplyDelete
  4. Very nice article. I have always needed this comprehensive introduction to cloning.

    ReplyDelete
  5. Thank you.Perfect article.

    ReplyDelete
  6. I just checked: C# does offer the correct solution for the type safety problem: http://msdn.microsoft.com/en-us/library/dd233060(v=vs.110).aspx

    Also, the iCloneable interface should not define if the implementers are cloned shallow or not. That is an implementation detail which should be encapsulated. Generally it's not even that clear cut: Some attributes are sensible to be cloned shallowly and others deeply, it's the class's author's decision which to apply where.

    ReplyDelete
  7. Very nice article - great and yet short introduction.

    I add two more links for well working cloning codes:
    1. Cloning by Reflection
    2. Cloning by Expression Trees

    The second link has beside the code also performance comparison of cloning by Serialization, Reflection and Expression Trees.

    ReplyDelete
  8. Your style is unique in comparison to other folks I have read stuff from.
    Many thanks for posting when you have the opportunity, Guess I will just bookmark this blog.wondershare filmora crack

    ReplyDelete
  9. Camtasia!
    PC Full Crack!
    I am very thankful for the effort put on by you, to help us, Thank you so much for the post it is very helpful, keep posting such type of Article.

    ReplyDelete
  10. Need for Speed: Undercover For Pc Download Game
    Thepcgameshere.com
    Need for Speed: Undercover For Pc Download is a supercar speediest car racing game. This game has an adventure for users who like to play it.

    ReplyDelete
  11. Ashes Cricket Game
    Ashes Cricket Game Download is the powerfully authorized computer game. Therefore, It cricket’s most prominent conflict.

    ReplyDelete
  12. MediaMonkey Gold
    https://windowsactivation.net/
    MediaMonkeyGold Serial Key is an excellent all-round program for recording and organising music and supports all popular audio formats.

    ReplyDelete
  13. In 2021, the world777 online gaming audience in India grew 28 per cent to reach Rs 101 billion or crore ( roughlyUS$1.3 billion), according to a report published in March 2022 by EY, a global professional services company, and the Federation of Indian Chambers of Commerce & Industry (FICCI).

    ReplyDelete
DECLARE

@imgString varchar(80),

@insertString varchar(3000),

@imgNumber int

SET @imgNumber = 1

WHILE (@imgNumber <= 100)

BEGIN

SET @imgString = 'D:\MPPICTURES\PP' + CONVERT(nvarchar,@imgNumber) + '.jpg'

SET @insertString= N'update tblEmp

set PICTURES = (SELECT * FROM OPENROWSET(BULK N''' +
Recovering SQL Server Database From Suspect Mode

Follow below steps to recover database from suspect mode:

ALTER DATABASE [database_name] SET EMERGENCY  DBCC checkdb('database_name')  ALTER DATABASE [database_name] SET SINGLE_USER WITH ROLLBACK IMMEDIATE  DBCC CheckDB ('database_name', REPAIR_ALLO
Click Here For Free Online E-Books
What Is LINQ to SQL?

LINQ to SQL is an O/RM (object relational mapping) implementation that ships in the .NET Framework "Orcas" release, and which allows you to model a relational database using .NET classes. You can then query the database using LINQ, as well as update/insert/delete data from it.
monthReceipts.Text = String.Format("{0:£#,##0.00}", Convert.ToDecimal(m_accin));

m_accin = Parameter Name
What is Multi-Targeting?

With the past few releases of Visual Studio, each Visual Studio release only supported a specific version of the .NET Framework. For example, VS 2002 only worked with .NET 1.0, VS 2003 only worked with .NET 1.1, and VS 2005 only worked with .NET 2.0.
Microsoft recently released a cool new ASP.NET server control - - that can be used for free with ASP.NET 3.5 to enable rich browser-based charting scenarios:

Download the free Microsoft Chart Controls

Download the VS 2008 Tool Support for the Chart Controls

Download the Microsoft Chart Controls S
--"TOOL_TYP_CODE" = COLUMN NAME

--"DMS_DCT_TOOL_TYPE" = TABLE

--"WBD0" = CODE LAST

SELECT

MAX(CONVERT(INTEGER,SUBSTRING(TOOL_TYP_CODE,5,4)))

FROM DMS_DCT_TOOL_TYPE

WHERE TOOL_TYP_CODE LIKE 'WBD0%'
To disable autorecovery in .net :

Go to Registry and change to 0 (zero) value of the following key:

HKEY_CURRENT_USER\Software\Microsoft\Microsoft SQL Server\90\Tools\Shell\General\AutoRecover\AutoRecover Enabled
Row_Number() over (Order by Emp_ID) as Serial
Que:- What’s the implicit name of the parameter that gets passed into the class’ set method?

Ans:- Value, and its datatype depends on whatever variable we’re changing.

Que:- How do you inherit from a class in C#?

Ans:- Place a colon and then the name of the base class.
Que:- What is the sequence in which ASP.NET events are processed ?

Ans:- Following is the sequence in which the events occur :-

* Page_Init.

* Page_Load.

* Control events.

* Page_Unload event.
In Windows applications written before the advent of .NET, developers used various methods for providing configuration information to applications, such as .INI files, System Registry, etc.
DECLARE @intFlag INT

SET @intFlag = 1

WHILE (@intFlag <=28)

BEGIN

UPDATE 'TABLE NAME'

SET 'Column Name' = '000000' -- Note: Column Name that you want to update.
Label1.Text = System.Text.RegularExpressions.Regex.Replace(objListTrn.CourseOutLine, "\n", "

", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
What is a Delegate?

When we talk about delegates in .NET then one thing that comes to our mind is what delegate means to a novice developer. In simple words we can say delegates are a .NET object which points to a method that matches its specific signature.
Introduction:

ASP.NET webforms provide excellent event driven programming model to developers. This does simplifies the overall design of your application but poses some problems of its own. For example, in traditional ASP you can easily pass values from one ASP page to another ASP page using POST.
Just like with golf, technology is as much about ensuring that your bad hits are recoverable as it is ensuring that you make great ones. We’re all going to have failures in our careers but avoiding the really big pitfalls will help you keep your company on the right growth path.
What's New in MSDN Code Gallery?
There are few rules to consider when determining when a year is a leap year. For instance, contrary to popular belief not all years divisible by 4 are leap years. For instance, the year 1900 was not a leap year. However, you needn't bother yourself about leap year rules...
Introduction:

In the IT world, software applications are being rapidly developed.
This article will show how you can Ajax with GridView to display popup messages when mouse moves over certain column. In the demo project I have added first column as an image column with a help icon in it.
What is an extender? The AJAX Control Toolkit uses extenders to provide additional capabilities that go beyond what the normal ASP.NET controls can do out-of-the-box. This is because these extenders use client-side script to perform animations, transformations, or other cool effects.
What is Silverlight?

Silverlight is a browser plug-in that that extends the web development experience far beyond the limitations of plain HTML and JavaScript. Being a Microsoft product, you might expect it to work best (or only) on Windows and Internet Explorer.
ASP.NET 2.0 has made quite a few enhancements over ASP.NET 1.x in terms of handling common client-side tasks. It has also created new classes, properties and method of working with JavaScript code.
.NET Framework 3.5 New Features
Cloning C# objects is one of those things that appears easy but is actually quite complicated with many "gotchas." This article describes the most common ways to clone a C# object.

Shallow vs. Deep Cloning

There are two types of object cloning: shallow and deep.
Google is expected to roll out the latest version of the Google Web Toolkit at its developer conference.

Google will hold its second major software developer conference May 28 and 29, delivering a host of new technology, services and advice for developers around the Google platform.
.NET Compact Framework

The .NET Compact Framework version 3.5 expands support for distributed mobile applications by including the Windows Communication Foundation (WCF) technology.
Microsoft SQL Server 2005 customers will have to upgrade from Service Pack 1 to an as-yet unavailable Service Pack 2 before their applications will be able to work with Vista or the Longhorn server.Microsoft's corporate customers may have another reason to take their time upgrading to Vista.
public class Class1

{

public Class1()

{

}

public int GetResult(ref string parameter1, int parameter2)

{

parameter1 = "Class1 did this";

return 1011;

}

}

public class Class2

{

public Class2()

{

}

public int GetResult(ref string parameter1, int parameter2)

{

parameter1 = "Class2 did
Subscribe
Subscribe
Favorite Links
Blog Archive
About Me
Loading
Dynamic Views theme. Powered by Blogger. Report Abuse.