Solved

Copy/Clone an object.

Posted on 2016-11-30
9
29 Views
Last Modified: 2016-12-01
I'm using a third party library that has methods/objects to create PDFs and to access a page in a PDF.   I want to be able to copy/clone an object that's part of this library that represents a PDF page.  Just doing an assignment from one variable to another merely references the same object.    

How can I do this?
0
Comment
Question by:HLRosenberger
  • 4
  • 4
9 Comments
 
LVL 44

Expert Comment

by:AndyAinscow
ID: 41907393
Something like
ob2 = ob1.Clone()
if that functionality exists in the library
0
 
LVL 1

Author Comment

by:HLRosenberger
ID: 41907404
.Clone does not exist.   And if I try to New an instance of this object, I get:  ".... Sub New(  As    ) is not accessible in this context because it is 'Friend'.
0
 
LVL 44

Expert Comment

by:AndyAinscow
ID: 41907461
Is there a copy function in the library?
0
 
LVL 1

Author Comment

by:HLRosenberger
ID: 41907508
no copy either. I thought maybe there was a generic .NET way to clone any object.
0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
LVL 44

Expert Comment

by:AndyAinscow
ID: 41907571
There is (with a caveat) - Clone - but it needs the object to implement the ICloneable interface.

https://msdn.microsoft.com/en-us/library/system.icloneable.clone(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1
0
 
LVL 33

Accepted Solution

by:
it_saige earned 500 total points
ID: 41907860
If your object supports serialization you can generate a clone from the serialized representation of the original object; e.g. -
static class Extensions
{
	public static T Clone<T>(this T source)
	{
		if (!typeof(T).IsSerializable)
			throw new ArgumentException("The type to be cloned must be serializable.", "source");

		if (object.ReferenceEquals(source, null))
			return default(T);

		IFormatter formatter = new BinaryFormatter();
		using (Stream stream = new MemoryStream())
		{
			formatter.Serialize(stream, source);
			stream.Seek(0, SeekOrigin.Begin);
			return (T)formatter.Deserialize(stream);
		}
	}
}

Open in new window

Example usage -
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace EE_Q28986373
{
	class Program
	{
		static void Main(string[] args)
		{
			Person bob = new Person() { ID = 1, FirstName = "Bob", LastName = "Smith" };
			Console.WriteLine("The original bob");
			Console.WriteLine(bob);
			Person bob2 = bob.Clone();
			Console.WriteLine("The cloned bob");
			Console.WriteLine(bob2);
			Console.WriteLine();
			Console.WriteLine("Are the original bob and the cloned bob equal? {0}", bob == bob2);
			Console.WriteLine("Are the original bob and the cloned bob the same object? {0}", object.ReferenceEquals(bob, bob2));
			Console.WriteLine();
			Console.WriteLine("Let's change the cloned bob's last name.");
			bob2.LastName = "Johnson";
			Console.WriteLine("The cloned bob");
			Console.WriteLine(bob2);
			Console.WriteLine("Are the original bob and the cloned bob equal? {0}", bob == bob2);
			Console.ReadLine();
		}
	}

	[Serializable]
	class Person
	{
		public int ID { get; set; }
		public string FirstName { get; set; }
		public string LastName { get; set; }

		public override string ToString()
		{
			return string.Format("{0} {1} [{2}]", FirstName, LastName, ID);
		}

		public override bool Equals(object obj)
		{
			if (obj == null || (obj.GetType() != GetType()))
				return false;

			return this == (obj as Person);
		}

		public bool Equals(Person person)
		{
			if (object.ReferenceEquals(person, null))
				return false;

			return this == person;
		}

		public override int GetHashCode()
		{
			return (ID != null ? ID.GetHashCode() : 0) ^ (FirstName != null ? FirstName.GetHashCode() : 0) ^ (LastName != null ? LastName.GetHashCode() : 0);
		}

		public static bool operator ==(Person lhs, Person rhs)
		{
			if (object.ReferenceEquals(lhs, rhs))
				return true;

			if (object.ReferenceEquals(lhs, null) || object.ReferenceEquals(rhs, null))
				return false;

			return (lhs.ID != null && rhs.ID != null ? lhs.ID.Equals(rhs.ID) : false) &&
				(lhs.FirstName != null && rhs.FirstName != null ? lhs.FirstName.Equals(rhs.FirstName) : false) &&
				(lhs.LastName != null && rhs.LastName != null ? lhs.LastName.Equals(rhs.LastName) : false);
		}

		public static bool operator !=(Person lhs, Person rhs)
		{
			return !(lhs == rhs);
		}
	}

	static class Extensions
	{
		public static T Clone<T>(this T source)
		{
			if (!typeof(T).IsSerializable)
				throw new ArgumentException("The type to be cloned must be serializable.", "source");

			if (object.ReferenceEquals(source, null))
				return default(T);

			IFormatter formatter = new BinaryFormatter();
			using (Stream stream = new MemoryStream())
			{
				formatter.Serialize(stream, source);
				stream.Seek(0, SeekOrigin.Begin);
				return (T)formatter.Deserialize(stream);
			}
		}
	}
}

Open in new window

Produces the following output -Capture.JPG
-saige-
0
 
LVL 1

Author Comment

by:HLRosenberger
ID: 41908698
Unfortunately, it's not serializable.
0
 
LVL 1

Author Closing Comment

by:HLRosenberger
ID: 41908700
Thanks!
0
 
LVL 44

Expert Comment

by:AndyAinscow
ID: 41908709
>>Unfortunately, it's not serializable.

So why have you accepted that as an answer in that case?
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
This Micro Tutorial will give you a basic overview how to record your screen with Microsoft Expression Encoder. This program is still free and open for the public to download. This will be demonstrated using Microsoft Expression Encoder 4.
With the power of JIRA, there's an unlimited number of ways you can customize it, use it and benefit from it. With that in mind, there's bound to be things that I wasn't able to cover in this course. With this summary we'll look at some places to go…

911 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now