Solved

Copy/Clone an object.

Posted on 2016-11-30
9
54 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Space-Age Communications Transitions to DevOps

ViaSat, a global provider of satellite and wireless communications, securely connects businesses, governments, and organizations to the Internet. Learn how ViaSat’s Network Solutions Engineer, drove the transition from a traditional network support to a DevOps-centric model.

 
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 34

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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Suggested Solutions

This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…
How to Install VMware Tools in Red Hat Enterprise Linux 6.4 (RHEL 6.4) Step-by-Step Tutorial

739 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