Solved

Copy/Clone an object.

Posted on 2016-11-30
9
10 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
Comment Utility
Something like
ob2 = ob1.Clone()
if that functionality exists in the library
0
 
LVL 1

Author Comment

by:HLRosenberger
Comment Utility
.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
Comment Utility
Is there a copy function in the library?
0
 
LVL 1

Author Comment

by:HLRosenberger
Comment Utility
no copy either. I thought maybe there was a generic .NET way to clone any object.
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 44

Expert Comment

by:AndyAinscow
Comment Utility
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 32

Accepted Solution

by:
it_saige earned 500 total points
Comment Utility
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
Comment Utility
Unfortunately, it's not serializable.
0
 
LVL 1

Author Closing Comment

by:HLRosenberger
Comment Utility
Thanks!
0
 
LVL 44

Expert Comment

by:AndyAinscow
Comment Utility
>>Unfortunately, it's not serializable.

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

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

743 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

17 Experts available now in Live!

Get 1:1 Help Now