Solved

Copy/Clone an object.

Posted on 2016-11-30
9
37 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
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 
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
 
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

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

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

Creating an analog clock UserControl seems fairly straight forward.  It is, after all, essentially just a circle with several lines in it!  Two common approaches for rendering an analog clock typically involve either manually calculating points with…
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 …
In a recent question (https://www.experts-exchange.com/questions/28997919/Pagination-in-Adobe-Acrobat.html) here at Experts Exchange, a member asked how to add page numbers to a PDF file using Adobe Acrobat XI Pro. This short video Micro Tutorial sh…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

803 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