Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Copy/Clone an object.

Posted on 2016-11-30
9
Medium Priority
?
72 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
Technology Partners: 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!

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

Learn Veeam advantages over legacy backup

Every day, more and more legacy backup customers switch to Veeam. Technologies designed for the client-server era cannot restore any IT service running in the hybrid cloud within seconds. Learn top Veeam advantages over legacy backup and get Veeam for the price of your renewal

Question has a verified solution.

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

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…
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…
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…

722 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