![]() |
Languages »
C# »
Generics
Intermediate
License: The Code Project Open License (CPOL)
Object Cloning Using Generic in C#By Kurush RastkarThis utility creates a new instance of your class using generic. |
C# (C# 2.0, C# 3.0), .NET (.NET 2.0, .NET 3.0), ASP.NET, Visual Studio (VS2005, VS2008)
|
||||||||
|
Advanced Search Add to IE Search |
|
|
|
||||||||||||||||
In one of my project I came across a situation which I needed to make a clone of an object and unfortunately C# doesn’t have such utility or maybe there is and simply I don’t know yet! Anyway, first I started with MSDN and look at the ICloneable interface … and then I find some interesting articles like this one: Base class for cloning an object in C#. However I finally decided to write my own Cloning Class using generic and XmlSerializer! The CloneManager is a simple class that can create a new instance of any class. Moreover your class doesn’t require having any attribute decoration!
All you have to do is to add reference to CloneManager project and create an instance of this class in your source code as shows below.
Code Example:
//Create an instance of clone manager IClone cloneManager = new CloneManager(); MyClass newInstance = cloneManager.Clone(instance);
The CloneManager implements IClone interface which exposes only one method. The Clone method simply serialize the instance into a memory stream and deserialize this stream to a new instance of object using XmlSerializer and returns that to the caller.
public interface IClone { T Clone(T instance) where T : class; } using System; using System.Xml.Serialization; using System.IO; namespace Demo.Clone { public class CloneManager:IClone { /// Clones the specified instance. /// Returns a new instance of an object. T IClone.Clone(T instance){ XmlSerializer serializer = new XmlSerializer(typeof(T)); MemoryStream stream = new MemoryStream(); serializer.Serialize(stream, instance); stream.Seek(0, SeekOrigin.Begin); return serializer.Deserialize(stream) as T; } } }
Happy coding!
| You must Sign In to use this message board. | |||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||
General
News
Question
Answer
Joke
Rant
Admin
|
PermaLink |
Privacy |
Terms of Use
Last Updated: 20 Apr 2008 Editor: |
Copyright 2008 by Kurush Rastkar Everything else Copyright © CodeProject, 1999-2009 Web21 | Advertise on the Code Project |