SlideShare a Scribd company logo
1 of 40
Download to read offline
Mohammad Shaker
mohammadshaker.com
C# Programming Course
@ZGTRShaker
2011, 2012, 2013, 2014
C# Starter
L07 – Objects Cloning
uses Object Cloning to save the whole engine state
The user can then switch back to any point in time!
See more of
@ http://mohammadshakergtr.wordpress.com/
and @ http://www.youtube.com/watch?v=FM3v0tbdKrs
Cloning Objects – The Concept
Shallow Clone VS Deep Clone
Cloning Objects
using System;
using System.Reflection;
namespace ConsoleApplicationCourseTest
{
class Mobile
{
public string Number { set; get; }
}
class MainClass
{
public static void Main(String[] args)
{
Mobile M1 = new Mobile(), M2 = new Mobile();
M1.Number = "0000";
M2.Number = "0001";
M2 = M1;
Console.WriteLine("M1 Num. {0} nM2 Num. {1}", M1.Number, M2.Number);
}
}
}
Cloning Objects
using System;
using System.Reflection;
namespace ConsoleApplicationCourseTest
{
class Mobile
{
public string Number { set; get; }
}
class MainClass
{
public static void Main(String[] args)
{
Mobile M1 = new Mobile(), M2 = new Mobile();
M1.Number = "0000";
M2.Number = "0001";
M2 = M1;
Console.WriteLine("M1 Num. {0} nM2 Num. {1}", M1.Number, M2.Number);
}
}
}
M1 Num. 0000
M2 Num. 0000
Press any key to continue...
Cloning Objects
using System;
using System.Reflection;
namespace ConsoleApplicationCourseTest
{
class Mobile
{
public string Number { set; get; }
}
class MainClass
{
public static void Main(String[] args)
{
Mobile M1 = new Mobile(), M2 = new Mobile();
M1.Number = "0000";
M2.Number = "0001";
M2 = M1;
Console.WriteLine("M1 Num. {0} nM2 Num. {1}", M1.Number, M2.Number);
}
}
}
M1 Num. 0000
M2 Num. 0000
Press any key to continue...
Cloning Objects
using System;
using System.Reflection;
namespace ConsoleApplicationCourseTest
{
class Mobile
{
public string Number { set; get; }
}
class MainClass
{
public static void Main(String[] args)
{
Mobile M1 = new Mobile(), M2 = new Mobile();
M1.Number = "0000";
M2.Number = "0001";
M2 = M1;
Console.WriteLine("M1 Num. {0} nM2 Num. {1}", M1.Number, M2.Number);
}
}
}
M1 Num. 0000
M2 Num. 0000
Press any key to continue...
Cloning Objects
using System;
using System.Reflection;
namespace ConsoleApplicationCourseTest
{
class Mobile
{
public string Number { set; get; }
}
class MainClass
{
public static void Main(String[] args)
{
Mobile M1 = new Mobile(), M2 = new Mobile();
M1.Number = "0000";
M2.Number = "0001";
M2 = M1;
Console.WriteLine("M1 Num. {0} nM2 Num. {1}", M1.Number, M2.Number);
}
}
}
M1 Num. 0000
M2 Num. 0000
Press any key to continue...
Cloning Objects
using System;
using System.Reflection;
namespace ConsoleApplicationCourseTest
{
class Mobile
{
public string Number { set; get; }
}
class MainClass
{
public static void Main(String[] args)
{
Mobile M1 = new Mobile(), M2 = new Mobile();
M1.Number = "0000";
M2.Number = "0001";
M2 = M1;
Console.WriteLine("M1 Num. {0} nM2 Num. {1}", M1.Number, M2.Number);
}
}
}
M1 Num. 0000
M2 Num. 0000
Press any key to continue...
Cloning Objects
using System;
using System.Reflection;
namespace ConsoleApplicationCourseTest
{
class Mobile
{
public string Number { set; get; }
}
class MainClass
{
public static void Main(String[] args)
{
Mobile M1 = new Mobile(), M2 = new Mobile();
M1.Number = "0000";
M2.Number = "0001";
M2 = M1;
Console.WriteLine("M1 Num. {0} nM2 Num. {1}", M1.Number, M2.Number);
}
}
}
M1 Num. 0000
M2 Num. 0000
Press any key to continue...
Cloning Objects
using System;
using System.Reflection;
namespace ConsoleApplicationCourseTest
{
class Mobile
{
public string Number { set; get; }
}
class MainClass
{
public static void Main(String[] args)
{
Mobile M1 = new Mobile(), M2 = new Mobile();
M1.Number = "0000";
M2.Number = M1.Number;
Console.WriteLine("M1 Num. {0} nM2 Num. {1}", M1.Number, M2.Number);
}
}
}
M1 Num. 0000
M2 Num. 0000
Press any key to continue...
Cloning Objects
using System;
using System.Reflection;
namespace ConsoleApplicationCourseTest
{
class Mobile
{
public string Number { set; get; }
}
class MainClass
{
public static void Main(String[] args)
{
Mobile M1 = new Mobile(), M2 = new Mobile();
M1.Number = "0000";
M2.Number = M1.Number;
Console.WriteLine("M1 Num. {0} nM2 Num. {1}", M1.Number, M2.Number);
}
}
}
M1 Num. 0000
M2 Num. 0000
Press any key to continue...
Cloning Objects
using System;
using System.Reflection;
namespace ConsoleApplicationCourseTest
{
class Mobile
{
public string Number { set; get; }
}
class MainClass
{
public static void Main(String[] args)
{
Mobile M1 = new Mobile(), M2 = new Mobile();
M1.Number = "0000";
M2.Number = M1.Number;
Console.WriteLine("M1 Num. {0} nM2 Num. {1}", M1.Number, M2.Number);
}
}
}
M1 Num. 0000
M2 Num. 0000
Press any key to continue...
Cloning Objects
using System;
using System.Reflection;
namespace ConsoleApplicationCourseTest
{
class Mobile
{
public string Number { set; get; }
}
class MainClass
{
public static void Main(String[] args)
{
Mobile M1 = new Mobile(), M2 = new Mobile();
M1.Number = "0000";
M2.Number = M1.Number;
Console.WriteLine("M1 Num. {0} nM2 Num. {1}", M1.Number, M2.Number);
}
}
}
M1 Num. 0000
M2 Num. 0000
Press any key to continue...
Try to Clone with IClonable interface
Cloning Objects
• ICloneable interface
• Another disadvantage of ICloneable is that the Clone method returns an object,
hence every Clone call requires a cast:
public interface ICloneable
{
object Clone();
}
Person joe = new Person();
joe.Name = "Joe Smith";
Person joeClone = (Person)joe.Clone();
namespace ConsoleApplicationCourseTest
{
class MainClass
{
public class Person : ICloneable
{
public string Name;
object ICloneable.Clone()
{
return this.Clone();
}
public Person Clone()
{
return (Person)this.MemberwiseClone();
}
}
public static void Main(String[] args)
{
Person joe = new Person();
joe.Name = "Joe Smith";
Person bob = (Person)joe.Clone();
Console.WriteLine("joe FullName: {0} nbob FullName: {1}", joe.Name, bob.Name);
bob.Name = "Bob PopUp";
Console.WriteLine("joe FullName: {0} nbob FullName: {1}", joe.Name, bob.Name);
}
}
}
namespace ConsoleApplicationCourseTest
{
class MainClass
{
public class Person : ICloneable
{
public string Name;
object ICloneable.Clone()
{
return this.Clone();
}
public Person Clone()
{
return (Person)this.MemberwiseClone();
}
}
public static void Main(String[] args)
{
Person joe = new Person();
joe.Name = "Joe Smith";
Person bob = (Person)joe.Clone();
Console.WriteLine("joe FullName: {0} nbob FullName: {1}", joe.Name, bob.Name);
bob.Name = "Bob PopUp";
Console.WriteLine("joe FullName: {0} nbob FullName: {1}", joe.Name, bob.Name);
}
}
}
namespace ConsoleApplicationCourseTest
{
class MainClass
{
public class Person : ICloneable
{
public string Name;
object ICloneable.Clone()
{
return this.Clone();
}
public Person Clone()
{
return (Person)this.MemberwiseClone();
}
}
public static void Main(String[] args)
{
Person joe = new Person();
joe.Name = "Joe Smith";
Person bob = (Person)joe.Clone();
Console.WriteLine("joe FullName: {0} nbob FullName: {1}", joe.Name, bob.Name);
bob.Name = "Bob PopUp";
Console.WriteLine("joe FullName: {0} nbob FullName: {1}", joe.Name, bob.Name);
}
}
}
namespace ConsoleApplicationCourseTest
{
class MainClass
{
public class Person : ICloneable
{
public string Name;
object ICloneable.Clone()
{
return this.Clone();
}
public Person Clone()
{
return (Person)this.MemberwiseClone();
}
}
public static void Main(String[] args)
{
Person joe = new Person();
joe.Name = "Joe Smith";
Person bob = (Person)joe.Clone();
Console.WriteLine("joe FullName: {0} nbob FullName: {1}", joe.Name, bob.Name);
bob.Name = "Bob PopUp";
Console.WriteLine("joe FullName: {0} nbob FullName: {1}", joe.Name, bob.Name);
}
}
}
namespace ConsoleApplicationCourseTest
{
class MainClass
{
public class Person : ICloneable
{
public string Name;
object ICloneable.Clone()
{
return this.Clone();
}
public Person Clone()
{
return (Person)this.MemberwiseClone();
}
}
public static void Main(String[] args)
{
Person joe = new Person();
joe.Name = "Joe Smith";
Person bob = (Person)joe.Clone();
Console.WriteLine("joe FullName: {0} nbob FullName: {1}", joe.Name, bob.Name);
bob.Name = "Bob PopUp";
Console.WriteLine("joe FullName: {0} nbob FullName: {1}", joe.Name, bob.Name);
}
}
}
namespace ConsoleApplicationCourseTest
{
class MainClass
{
public class Person : ICloneable
{
public string Name;
object ICloneable.Clone()
{
return this.Clone();
}
public Person Clone()
{
return (Person)this.MemberwiseClone();
}
}
public static void Main(String[] args)
{
Person joe = new Person();
joe.Name = "Joe Smith";
Person bob = (Person)joe.Clone();
Console.WriteLine("joe FullName: {0} nbob FullName: {1}", joe.Name, bob.Name);
bob.Name = "Bob PopUp";
Console.WriteLine("joe FullName: {0} nbob FullName: {1}", joe.Name, bob.Name);
}
}
}
namespace ConsoleApplicationCourseTest
{
class MainClass
{
public class Person : ICloneable
{
public string Name;
object ICloneable.Clone()
{
return this.Clone();
}
public Person Clone()
{
return (Person)this.MemberwiseClone();
}
}
public static void Main(String[] args)
{
Person joe = new Person();
joe.Name = "Joe Smith";
Person bob = (Person)joe.Clone();
Console.WriteLine("joe FullName: {0} nbob FullName: {1}", joe.Name, bob.Name);
bob.Name = "Bob PopUp";
Console.WriteLine("joe FullName: {0} nbob FullName: {1}", joe.Name, bob.Name);
}
}
}
joe FullName: Joe Smith
bob FullName: Joe Smith
joe FullName: Joe Smith
bob FullName: Bob PopUp
Press any key to continue...
namespace ConsoleApplicationCourseTest
{
class MainClass
{
public class Person : ICloneable
{
public string Name;
object ICloneable.Clone()
{
return this.Clone();
}
public Person Clone()
{
return (Person)this.MemberwiseClone();
}
}
public static void Main(String[] args)
{
Person joe = new Person();
joe.Name = "Joe Smith";
Person bob = (Person)joe.Clone();
Console.WriteLine("joe FullName: {0} nbob FullName: {1}", joe.Name, bob.Name);
bob.Name = "Bob PopUp";
Console.WriteLine("joe FullName: {0} nbob FullName: {1}", joe.Name, bob.Name);
}
}
}
joe FullName: Joe Smith
bob FullName: Joe Smith
joe FullName: Joe Smith
bob FullName: Bob PopUp
Press any key to continue...
But this is all a headache!
The fastest way to deep clone..
The fastest way to deep clone
The fastest way to deep clone
[Serialization]
public static class ObjectCopier
{
/// <summary>
/// Perform a deep Copy of the object.
/// </summary>
/// <typeparam name="T">The type of object being copied.</typeparam>
/// <param name="source">The object instance to copy.</param>
/// <returns>The copied object.</returns>
public static T Clone<T>(T source)
{
if (!typeof(T).IsSerializable)
{
throw new ArgumentException("The type must be serializable.", "source");
}
// Don't serialize a null object, simply return the default for that object
if (Object.ReferenceEquals(source, null))
{
return default(T);
}
IFormatter formatter = new BinaryFormatter();
Stream stream = new MemoryStream();
using (stream)
{
formatter.Serialize(stream, source);
stream.Seek(0, SeekOrigin.Begin);
return (T)formatter.Deserialize(stream);
}
}
}
public static class ObjectCopier
{
/// <summary>
/// Perform a deep Copy of the object.
/// </summary>
/// <typeparam name="T">The type of object being copied.</typeparam>
/// <param name="source">The object instance to copy.</param>
/// <returns>The copied object.</returns>
public static T Clone<T>(T source)
{
if (!typeof(T).IsSerializable)
{
throw new ArgumentException("The type must be serializable.", "source");
}
// Don't serialize a null object, simply return the default for that object
if (Object.ReferenceEquals(source, null))
{
return default(T);
}
IFormatter formatter = new BinaryFormatter();
Stream stream = new MemoryStream();
using (stream)
{
formatter.Serialize(stream, source);
stream.Seek(0, SeekOrigin.Begin);
return (T)formatter.Deserialize(stream);
}
}
}
public static class ObjectCopier
{
/// <summary>
/// Perform a deep Copy of the object.
/// </summary>
/// <typeparam name="T">The type of object being copied.</typeparam>
/// <param name="source">The object instance to copy.</param>
/// <returns>The copied object.</returns>
public static T Clone<T>(T source)
{
if (!typeof(T).IsSerializable)
{
throw new ArgumentException("The type must be serializable.", "source");
}
// Don't serialize a null object, simply return the default for that object
if (Object.ReferenceEquals(source, null))
{
return default(T);
}
IFormatter formatter = new BinaryFormatter();
Stream stream = new MemoryStream();
using (stream)
{
formatter.Serialize(stream, source);
stream.Seek(0, SeekOrigin.Begin);
return (T)formatter.Deserialize(stream);
}
}
}
public static class ObjectCopier
{
/// <summary>
/// Perform a deep Copy of the object.
/// </summary>
/// <typeparam name="T">The type of object being copied.</typeparam>
/// <param name="source">The object instance to copy.</param>
/// <returns>The copied object.</returns>
public static T Clone<T>(T source)
{
if (!typeof(T).IsSerializable)
{
throw new ArgumentException("The type must be serializable.", "source");
}
// Don't serialize a null object, simply return the default for that object
if (Object.ReferenceEquals(source, null))
{
return default(T);
}
IFormatter formatter = new BinaryFormatter();
Stream stream = new MemoryStream();
using (stream)
{
formatter.Serialize(stream, source);
stream.Seek(0, SeekOrigin.Begin);
return (T)formatter.Deserialize(stream);
}
}
}
public static class ObjectCopier
{
/// <summary>
/// Perform a deep Copy of the object.
/// </summary>
/// <typeparam name="T">The type of object being copied.</typeparam>
/// <param name="source">The object instance to copy.</param>
/// <returns>The copied object.</returns>
public static T Clone<T>(T source)
{
if (!typeof(T).IsSerializable)
{
throw new ArgumentException("The type must be serializable.", "source");
}
// Don't serialize a null object, simply return the default for that object
if (Object.ReferenceEquals(source, null))
{
return default(T);
}
IFormatter formatter = new BinaryFormatter();
Stream stream = new MemoryStream();
using (stream)
{
formatter.Serialize(stream, source);
stream.Seek(0, SeekOrigin.Begin);
return (T)formatter.Deserialize(stream);
}
}
}
public static class ObjectCopier
{
/// <summary>
/// Perform a deep Copy of the object.
/// </summary>
/// <typeparam name="T">The type of object being copied.</typeparam>
/// <param name="source">The object instance to copy.</param>
/// <returns>The copied object.</returns>
public static T Clone<T>(T source)
{
if (!typeof(T).IsSerializable)
{
throw new ArgumentException("The type must be serializable.", "source");
}
// Don't serialize a null object, simply return the default for that object
if (Object.ReferenceEquals(source, null))
{
return default(T);
}
IFormatter formatter = new BinaryFormatter();
Stream stream = new MemoryStream();
using (stream)
{
formatter.Serialize(stream, source);
stream.Seek(0, SeekOrigin.Begin);
return (T)formatter.Deserialize(stream);
}
}
}
End of Course
Go and have some fun and come back for the next
Advanced C# Course
Take a Look on my other courses
@ http://www.slideshare.net/ZGTRZGTR
Available courses to the date of this slide:
http://www.mohammadshaker.com
mohammadshakergtr@gmail.com
https://twitter.com/ZGTRShaker @ZGTRShaker
https://de.linkedin.com/pub/mohammad-shaker/30/122/128/
http://www.slideshare.net/ZGTRZGTR
https://www.goodreads.com/user/show/11193121-mohammad-shaker
https://plus.google.com/u/0/+MohammadShaker/
https://www.youtube.com/channel/UCvJUfadMoEaZNWdagdMyCRA
http://mohammadshakergtr.wordpress.com/
C# Starter L07-Objects Cloning

More Related Content

What's hot

The art of reverse engineering flash exploits
The art of reverse engineering flash exploitsThe art of reverse engineering flash exploits
The art of reverse engineering flash exploits
Priyanka Aash
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
Soumya Behera
 
Important java programs(collection+file)
Important java programs(collection+file)Important java programs(collection+file)
Important java programs(collection+file)
Alok Kumar
 

What's hot (20)

Ditec esoft C# project
Ditec esoft C# project Ditec esoft C# project
Ditec esoft C# project
 
The art of reverse engineering flash exploits
The art of reverse engineering flash exploitsThe art of reverse engineering flash exploits
The art of reverse engineering flash exploits
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
 
C++ Windows Forms L02 - Controls P1
C++ Windows Forms L02 - Controls P1C++ Windows Forms L02 - Controls P1
C++ Windows Forms L02 - Controls P1
 
Class method
Class methodClass method
Class method
 
C++ Windows Forms L11 - Inheritance
C++ Windows Forms L11 - Inheritance C++ Windows Forms L11 - Inheritance
C++ Windows Forms L11 - Inheritance
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
 
Chat Room System using Java Swing
Chat Room System using Java SwingChat Room System using Java Swing
Chat Room System using Java Swing
 
C++ Windows Forms L05 - Controls P4
C++ Windows Forms L05 - Controls P4C++ Windows Forms L05 - Controls P4
C++ Windows Forms L05 - Controls P4
 
final project for C#
final project for C#final project for C#
final project for C#
 
Vb.net iv
Vb.net ivVb.net iv
Vb.net iv
 
Java Programs
Java ProgramsJava Programs
Java Programs
 
Kotlin puzzler
Kotlin puzzlerKotlin puzzler
Kotlin puzzler
 
JDBC (JAVA Database Connectivity)
JDBC (JAVA Database Connectivity)JDBC (JAVA Database Connectivity)
JDBC (JAVA Database Connectivity)
 
Python functions
Python functionsPython functions
Python functions
 
Bot builder v4 HOL
Bot builder v4 HOLBot builder v4 HOL
Bot builder v4 HOL
 
Advanced Java - Praticals
Advanced Java - PraticalsAdvanced Java - Praticals
Advanced Java - Praticals
 
Advance Java Programs skeleton
Advance Java Programs skeletonAdvance Java Programs skeleton
Advance Java Programs skeleton
 
Java_practical_handbook
Java_practical_handbookJava_practical_handbook
Java_practical_handbook
 
Important java programs(collection+file)
Important java programs(collection+file)Important java programs(collection+file)
Important java programs(collection+file)
 

Viewers also liked

XNA L11–Shaders Part 2
XNA L11–Shaders Part 2XNA L11–Shaders Part 2
XNA L11–Shaders Part 2
Mohammad Shaker
 
XNA L10–Shaders Part 1
XNA L10–Shaders Part 1XNA L10–Shaders Part 1
XNA L10–Shaders Part 1
Mohammad Shaker
 
WPF L03-3D Rendering and 3D Animation
WPF L03-3D Rendering and 3D AnimationWPF L03-3D Rendering and 3D Animation
WPF L03-3D Rendering and 3D Animation
Mohammad Shaker
 
WPF L01-Layouts, Controls, Styles and Templates
WPF L01-Layouts, Controls, Styles and TemplatesWPF L01-Layouts, Controls, Styles and Templates
WPF L01-Layouts, Controls, Styles and Templates
Mohammad Shaker
 
XNA L02–Basic Matrices and Transformations
XNA L02–Basic Matrices and TransformationsXNA L02–Basic Matrices and Transformations
XNA L02–Basic Matrices and Transformations
Mohammad Shaker
 

Viewers also liked (18)

Indie Series 03: Becoming an Indie
Indie Series 03: Becoming an IndieIndie Series 03: Becoming an Indie
Indie Series 03: Becoming an Indie
 
XNA L11–Shaders Part 2
XNA L11–Shaders Part 2XNA L11–Shaders Part 2
XNA L11–Shaders Part 2
 
Delphi L02 Controls P1
Delphi L02 Controls P1Delphi L02 Controls P1
Delphi L02 Controls P1
 
XNA L10–Shaders Part 1
XNA L10–Shaders Part 1XNA L10–Shaders Part 1
XNA L10–Shaders Part 1
 
Utilizing Kinect Control for a More Immersive Interaction with 3D Environment
Utilizing Kinect Control for a More Immersive Interaction with 3D EnvironmentUtilizing Kinect Control for a More Immersive Interaction with 3D Environment
Utilizing Kinect Control for a More Immersive Interaction with 3D Environment
 
C# Advanced L09-HTML5+ASP
C# Advanced L09-HTML5+ASPC# Advanced L09-HTML5+ASP
C# Advanced L09-HTML5+ASP
 
WPF L03-3D Rendering and 3D Animation
WPF L03-3D Rendering and 3D AnimationWPF L03-3D Rendering and 3D Animation
WPF L03-3D Rendering and 3D Animation
 
Android L01 - Warm Up
Android L01 - Warm UpAndroid L01 - Warm Up
Android L01 - Warm Up
 
C# Advanced L10-Workflow Foundation
C# Advanced L10-Workflow FoundationC# Advanced L10-Workflow Foundation
C# Advanced L10-Workflow Foundation
 
WPF L01-Layouts, Controls, Styles and Templates
WPF L01-Layouts, Controls, Styles and TemplatesWPF L01-Layouts, Controls, Styles and Templates
WPF L01-Layouts, Controls, Styles and Templates
 
Interaction Design L06 - Tricks with Psychology
Interaction Design L06 - Tricks with PsychologyInteraction Design L06 - Tricks with Psychology
Interaction Design L06 - Tricks with Psychology
 
C# Advanced L08-Networking+WCF
C# Advanced L08-Networking+WCFC# Advanced L08-Networking+WCF
C# Advanced L08-Networking+WCF
 
Short, Matters, Love - Passioneers Event 2015
Short, Matters, Love -  Passioneers Event 2015Short, Matters, Love -  Passioneers Event 2015
Short, Matters, Love - Passioneers Event 2015
 
C# Starter L06-Delegates, Event Handling and Extension Methods
C# Starter L06-Delegates, Event Handling and Extension MethodsC# Starter L06-Delegates, Event Handling and Extension Methods
C# Starter L06-Delegates, Event Handling and Extension Methods
 
OpenGL Starter L02
OpenGL Starter L02OpenGL Starter L02
OpenGL Starter L02
 
Car Dynamics with ABS, ESP and GPS Systems
Car Dynamics with ABS, ESP and GPS SystemsCar Dynamics with ABS, ESP and GPS Systems
Car Dynamics with ABS, ESP and GPS Systems
 
XNA L02–Basic Matrices and Transformations
XNA L02–Basic Matrices and TransformationsXNA L02–Basic Matrices and Transformations
XNA L02–Basic Matrices and Transformations
 
Ultra Fast, Cross Genre, Procedural Content Generation in Games [Master Thesis]
Ultra Fast, Cross Genre, Procedural Content Generation in Games [Master Thesis]Ultra Fast, Cross Genre, Procedural Content Generation in Games [Master Thesis]
Ultra Fast, Cross Genre, Procedural Content Generation in Games [Master Thesis]
 

Similar to C# Starter L07-Objects Cloning

C# Starter L02-Classes and Objects
C# Starter L02-Classes and ObjectsC# Starter L02-Classes and Objects
C# Starter L02-Classes and Objects
Mohammad Shaker
 
wk2utility classes.zipApplicationUtilities.csusing System.docx
wk2utility classes.zipApplicationUtilities.csusing System.docxwk2utility classes.zipApplicationUtilities.csusing System.docx
wk2utility classes.zipApplicationUtilities.csusing System.docx
ericbrooks84875
 
Intro to object oriented programming
Intro to object oriented programmingIntro to object oriented programming
Intro to object oriented programming
David Giard
 

Similar to C# Starter L07-Objects Cloning (20)

C# Starter L02-Classes and Objects
C# Starter L02-Classes and ObjectsC# Starter L02-Classes and Objects
C# Starter L02-Classes and Objects
 
iOS Automation Primitives
iOS Automation PrimitivesiOS Automation Primitives
iOS Automation Primitives
 
Owasp orlando, april 13, 2016
Owasp orlando, april 13, 2016Owasp orlando, april 13, 2016
Owasp orlando, april 13, 2016
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java Programming
 
Java day 2016.pptx
Java day 2016.pptxJava day 2016.pptx
Java day 2016.pptx
 
Kotlin for android
Kotlin for androidKotlin for android
Kotlin for android
 
c#(loops,arrays)
c#(loops,arrays)c#(loops,arrays)
c#(loops,arrays)
 
Object-oriented Basics
Object-oriented BasicsObject-oriented Basics
Object-oriented Basics
 
Using Reflections and Automatic Code Generation
Using Reflections and Automatic Code GenerationUsing Reflections and Automatic Code Generation
Using Reflections and Automatic Code Generation
 
War Simulation
War SimulationWar Simulation
War Simulation
 
Hems
HemsHems
Hems
 
Dotnet 18
Dotnet 18Dotnet 18
Dotnet 18
 
Ocl 09
Ocl 09Ocl 09
Ocl 09
 
wk2utility classes.zipApplicationUtilities.csusing System.docx
wk2utility classes.zipApplicationUtilities.csusing System.docxwk2utility classes.zipApplicationUtilities.csusing System.docx
wk2utility classes.zipApplicationUtilities.csusing System.docx
 
Kotlin / Android Update
Kotlin / Android UpdateKotlin / Android Update
Kotlin / Android Update
 
Dlr
DlrDlr
Dlr
 
Painless Persistence with Realm
Painless Persistence with RealmPainless Persistence with Realm
Painless Persistence with Realm
 
Java oops features
Java oops featuresJava oops features
Java oops features
 
4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it
4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it
4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it
 
Intro to object oriented programming
Intro to object oriented programmingIntro to object oriented programming
Intro to object oriented programming
 

More from Mohammad Shaker

More from Mohammad Shaker (20)

12 Rules You Should to Know as a Syrian Graduate
12 Rules You Should to Know as a Syrian Graduate12 Rules You Should to Know as a Syrian Graduate
12 Rules You Should to Know as a Syrian Graduate
 
Unity L01 - Game Development
Unity L01 - Game DevelopmentUnity L01 - Game Development
Unity L01 - Game Development
 
Android L07 - Touch, Screen and Wearables
Android L07 - Touch, Screen and WearablesAndroid L07 - Touch, Screen and Wearables
Android L07 - Touch, Screen and Wearables
 
Interaction Design L03 - Color
Interaction Design L03 - ColorInteraction Design L03 - Color
Interaction Design L03 - Color
 
Interaction Design L05 - Typography
Interaction Design L05 - TypographyInteraction Design L05 - Typography
Interaction Design L05 - Typography
 
Interaction Design L04 - Materialise and Coupling
Interaction Design L04 - Materialise and CouplingInteraction Design L04 - Materialise and Coupling
Interaction Design L04 - Materialise and Coupling
 
Android L05 - Storage
Android L05 - StorageAndroid L05 - Storage
Android L05 - Storage
 
Android L04 - Notifications and Threading
Android L04 - Notifications and ThreadingAndroid L04 - Notifications and Threading
Android L04 - Notifications and Threading
 
Android L09 - Windows Phone and iOS
Android L09 - Windows Phone and iOSAndroid L09 - Windows Phone and iOS
Android L09 - Windows Phone and iOS
 
Interaction Design L01 - Mobile Constraints
Interaction Design L01 - Mobile ConstraintsInteraction Design L01 - Mobile Constraints
Interaction Design L01 - Mobile Constraints
 
Interaction Design L02 - Pragnanz and Grids
Interaction Design L02 - Pragnanz and GridsInteraction Design L02 - Pragnanz and Grids
Interaction Design L02 - Pragnanz and Grids
 
Android L10 - Stores and Gaming
Android L10 - Stores and GamingAndroid L10 - Stores and Gaming
Android L10 - Stores and Gaming
 
Android L06 - Cloud / Parse
Android L06 - Cloud / ParseAndroid L06 - Cloud / Parse
Android L06 - Cloud / Parse
 
Android L08 - Google Maps and Utilities
Android L08 - Google Maps and UtilitiesAndroid L08 - Google Maps and Utilities
Android L08 - Google Maps and Utilities
 
Android L03 - Styles and Themes
Android L03 - Styles and Themes Android L03 - Styles and Themes
Android L03 - Styles and Themes
 
Android L02 - Activities and Adapters
Android L02 - Activities and AdaptersAndroid L02 - Activities and Adapters
Android L02 - Activities and Adapters
 
Indie Series 01: Intro to Games
Indie Series 01: Intro to GamesIndie Series 01: Intro to Games
Indie Series 01: Intro to Games
 
Indie Series 04: The Making of SyncSeven
Indie Series 04: The Making of SyncSevenIndie Series 04: The Making of SyncSeven
Indie Series 04: The Making of SyncSeven
 
Indie Series 02: AI and Recent Advances in Games
Indie Series 02: AI and Recent Advances in GamesIndie Series 02: AI and Recent Advances in Games
Indie Series 02: AI and Recent Advances in Games
 
Roboconf DSL Advanced Software Engineering
Roboconf DSL Advanced Software EngineeringRoboconf DSL Advanced Software Engineering
Roboconf DSL Advanced Software Engineering
 

Recently uploaded

AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 

Recently uploaded (20)

AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Pharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyPharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodology
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 

C# Starter L07-Objects Cloning

  • 1. Mohammad Shaker mohammadshaker.com C# Programming Course @ZGTRShaker 2011, 2012, 2013, 2014 C# Starter L07 – Objects Cloning
  • 2. uses Object Cloning to save the whole engine state The user can then switch back to any point in time!
  • 3. See more of @ http://mohammadshakergtr.wordpress.com/ and @ http://www.youtube.com/watch?v=FM3v0tbdKrs
  • 4. Cloning Objects – The Concept
  • 5. Shallow Clone VS Deep Clone
  • 6. Cloning Objects using System; using System.Reflection; namespace ConsoleApplicationCourseTest { class Mobile { public string Number { set; get; } } class MainClass { public static void Main(String[] args) { Mobile M1 = new Mobile(), M2 = new Mobile(); M1.Number = "0000"; M2.Number = "0001"; M2 = M1; Console.WriteLine("M1 Num. {0} nM2 Num. {1}", M1.Number, M2.Number); } } }
  • 7. Cloning Objects using System; using System.Reflection; namespace ConsoleApplicationCourseTest { class Mobile { public string Number { set; get; } } class MainClass { public static void Main(String[] args) { Mobile M1 = new Mobile(), M2 = new Mobile(); M1.Number = "0000"; M2.Number = "0001"; M2 = M1; Console.WriteLine("M1 Num. {0} nM2 Num. {1}", M1.Number, M2.Number); } } } M1 Num. 0000 M2 Num. 0000 Press any key to continue...
  • 8. Cloning Objects using System; using System.Reflection; namespace ConsoleApplicationCourseTest { class Mobile { public string Number { set; get; } } class MainClass { public static void Main(String[] args) { Mobile M1 = new Mobile(), M2 = new Mobile(); M1.Number = "0000"; M2.Number = "0001"; M2 = M1; Console.WriteLine("M1 Num. {0} nM2 Num. {1}", M1.Number, M2.Number); } } } M1 Num. 0000 M2 Num. 0000 Press any key to continue...
  • 9. Cloning Objects using System; using System.Reflection; namespace ConsoleApplicationCourseTest { class Mobile { public string Number { set; get; } } class MainClass { public static void Main(String[] args) { Mobile M1 = new Mobile(), M2 = new Mobile(); M1.Number = "0000"; M2.Number = "0001"; M2 = M1; Console.WriteLine("M1 Num. {0} nM2 Num. {1}", M1.Number, M2.Number); } } } M1 Num. 0000 M2 Num. 0000 Press any key to continue...
  • 10. Cloning Objects using System; using System.Reflection; namespace ConsoleApplicationCourseTest { class Mobile { public string Number { set; get; } } class MainClass { public static void Main(String[] args) { Mobile M1 = new Mobile(), M2 = new Mobile(); M1.Number = "0000"; M2.Number = "0001"; M2 = M1; Console.WriteLine("M1 Num. {0} nM2 Num. {1}", M1.Number, M2.Number); } } } M1 Num. 0000 M2 Num. 0000 Press any key to continue...
  • 11. Cloning Objects using System; using System.Reflection; namespace ConsoleApplicationCourseTest { class Mobile { public string Number { set; get; } } class MainClass { public static void Main(String[] args) { Mobile M1 = new Mobile(), M2 = new Mobile(); M1.Number = "0000"; M2.Number = "0001"; M2 = M1; Console.WriteLine("M1 Num. {0} nM2 Num. {1}", M1.Number, M2.Number); } } } M1 Num. 0000 M2 Num. 0000 Press any key to continue...
  • 12. Cloning Objects using System; using System.Reflection; namespace ConsoleApplicationCourseTest { class Mobile { public string Number { set; get; } } class MainClass { public static void Main(String[] args) { Mobile M1 = new Mobile(), M2 = new Mobile(); M1.Number = "0000"; M2.Number = "0001"; M2 = M1; Console.WriteLine("M1 Num. {0} nM2 Num. {1}", M1.Number, M2.Number); } } } M1 Num. 0000 M2 Num. 0000 Press any key to continue...
  • 13. Cloning Objects using System; using System.Reflection; namespace ConsoleApplicationCourseTest { class Mobile { public string Number { set; get; } } class MainClass { public static void Main(String[] args) { Mobile M1 = new Mobile(), M2 = new Mobile(); M1.Number = "0000"; M2.Number = M1.Number; Console.WriteLine("M1 Num. {0} nM2 Num. {1}", M1.Number, M2.Number); } } } M1 Num. 0000 M2 Num. 0000 Press any key to continue...
  • 14. Cloning Objects using System; using System.Reflection; namespace ConsoleApplicationCourseTest { class Mobile { public string Number { set; get; } } class MainClass { public static void Main(String[] args) { Mobile M1 = new Mobile(), M2 = new Mobile(); M1.Number = "0000"; M2.Number = M1.Number; Console.WriteLine("M1 Num. {0} nM2 Num. {1}", M1.Number, M2.Number); } } } M1 Num. 0000 M2 Num. 0000 Press any key to continue...
  • 15. Cloning Objects using System; using System.Reflection; namespace ConsoleApplicationCourseTest { class Mobile { public string Number { set; get; } } class MainClass { public static void Main(String[] args) { Mobile M1 = new Mobile(), M2 = new Mobile(); M1.Number = "0000"; M2.Number = M1.Number; Console.WriteLine("M1 Num. {0} nM2 Num. {1}", M1.Number, M2.Number); } } } M1 Num. 0000 M2 Num. 0000 Press any key to continue...
  • 16. Cloning Objects using System; using System.Reflection; namespace ConsoleApplicationCourseTest { class Mobile { public string Number { set; get; } } class MainClass { public static void Main(String[] args) { Mobile M1 = new Mobile(), M2 = new Mobile(); M1.Number = "0000"; M2.Number = M1.Number; Console.WriteLine("M1 Num. {0} nM2 Num. {1}", M1.Number, M2.Number); } } } M1 Num. 0000 M2 Num. 0000 Press any key to continue...
  • 17. Try to Clone with IClonable interface
  • 18. Cloning Objects • ICloneable interface • Another disadvantage of ICloneable is that the Clone method returns an object, hence every Clone call requires a cast: public interface ICloneable { object Clone(); } Person joe = new Person(); joe.Name = "Joe Smith"; Person joeClone = (Person)joe.Clone();
  • 19. namespace ConsoleApplicationCourseTest { class MainClass { public class Person : ICloneable { public string Name; object ICloneable.Clone() { return this.Clone(); } public Person Clone() { return (Person)this.MemberwiseClone(); } } public static void Main(String[] args) { Person joe = new Person(); joe.Name = "Joe Smith"; Person bob = (Person)joe.Clone(); Console.WriteLine("joe FullName: {0} nbob FullName: {1}", joe.Name, bob.Name); bob.Name = "Bob PopUp"; Console.WriteLine("joe FullName: {0} nbob FullName: {1}", joe.Name, bob.Name); } } }
  • 20. namespace ConsoleApplicationCourseTest { class MainClass { public class Person : ICloneable { public string Name; object ICloneable.Clone() { return this.Clone(); } public Person Clone() { return (Person)this.MemberwiseClone(); } } public static void Main(String[] args) { Person joe = new Person(); joe.Name = "Joe Smith"; Person bob = (Person)joe.Clone(); Console.WriteLine("joe FullName: {0} nbob FullName: {1}", joe.Name, bob.Name); bob.Name = "Bob PopUp"; Console.WriteLine("joe FullName: {0} nbob FullName: {1}", joe.Name, bob.Name); } } }
  • 21. namespace ConsoleApplicationCourseTest { class MainClass { public class Person : ICloneable { public string Name; object ICloneable.Clone() { return this.Clone(); } public Person Clone() { return (Person)this.MemberwiseClone(); } } public static void Main(String[] args) { Person joe = new Person(); joe.Name = "Joe Smith"; Person bob = (Person)joe.Clone(); Console.WriteLine("joe FullName: {0} nbob FullName: {1}", joe.Name, bob.Name); bob.Name = "Bob PopUp"; Console.WriteLine("joe FullName: {0} nbob FullName: {1}", joe.Name, bob.Name); } } }
  • 22. namespace ConsoleApplicationCourseTest { class MainClass { public class Person : ICloneable { public string Name; object ICloneable.Clone() { return this.Clone(); } public Person Clone() { return (Person)this.MemberwiseClone(); } } public static void Main(String[] args) { Person joe = new Person(); joe.Name = "Joe Smith"; Person bob = (Person)joe.Clone(); Console.WriteLine("joe FullName: {0} nbob FullName: {1}", joe.Name, bob.Name); bob.Name = "Bob PopUp"; Console.WriteLine("joe FullName: {0} nbob FullName: {1}", joe.Name, bob.Name); } } }
  • 23. namespace ConsoleApplicationCourseTest { class MainClass { public class Person : ICloneable { public string Name; object ICloneable.Clone() { return this.Clone(); } public Person Clone() { return (Person)this.MemberwiseClone(); } } public static void Main(String[] args) { Person joe = new Person(); joe.Name = "Joe Smith"; Person bob = (Person)joe.Clone(); Console.WriteLine("joe FullName: {0} nbob FullName: {1}", joe.Name, bob.Name); bob.Name = "Bob PopUp"; Console.WriteLine("joe FullName: {0} nbob FullName: {1}", joe.Name, bob.Name); } } }
  • 24. namespace ConsoleApplicationCourseTest { class MainClass { public class Person : ICloneable { public string Name; object ICloneable.Clone() { return this.Clone(); } public Person Clone() { return (Person)this.MemberwiseClone(); } } public static void Main(String[] args) { Person joe = new Person(); joe.Name = "Joe Smith"; Person bob = (Person)joe.Clone(); Console.WriteLine("joe FullName: {0} nbob FullName: {1}", joe.Name, bob.Name); bob.Name = "Bob PopUp"; Console.WriteLine("joe FullName: {0} nbob FullName: {1}", joe.Name, bob.Name); } } }
  • 25. namespace ConsoleApplicationCourseTest { class MainClass { public class Person : ICloneable { public string Name; object ICloneable.Clone() { return this.Clone(); } public Person Clone() { return (Person)this.MemberwiseClone(); } } public static void Main(String[] args) { Person joe = new Person(); joe.Name = "Joe Smith"; Person bob = (Person)joe.Clone(); Console.WriteLine("joe FullName: {0} nbob FullName: {1}", joe.Name, bob.Name); bob.Name = "Bob PopUp"; Console.WriteLine("joe FullName: {0} nbob FullName: {1}", joe.Name, bob.Name); } } } joe FullName: Joe Smith bob FullName: Joe Smith joe FullName: Joe Smith bob FullName: Bob PopUp Press any key to continue...
  • 26. namespace ConsoleApplicationCourseTest { class MainClass { public class Person : ICloneable { public string Name; object ICloneable.Clone() { return this.Clone(); } public Person Clone() { return (Person)this.MemberwiseClone(); } } public static void Main(String[] args) { Person joe = new Person(); joe.Name = "Joe Smith"; Person bob = (Person)joe.Clone(); Console.WriteLine("joe FullName: {0} nbob FullName: {1}", joe.Name, bob.Name); bob.Name = "Bob PopUp"; Console.WriteLine("joe FullName: {0} nbob FullName: {1}", joe.Name, bob.Name); } } } joe FullName: Joe Smith bob FullName: Joe Smith joe FullName: Joe Smith bob FullName: Bob PopUp Press any key to continue...
  • 27. But this is all a headache!
  • 28. The fastest way to deep clone..
  • 29. The fastest way to deep clone
  • 30. The fastest way to deep clone [Serialization]
  • 31. public static class ObjectCopier { /// <summary> /// Perform a deep Copy of the object. /// </summary> /// <typeparam name="T">The type of object being copied.</typeparam> /// <param name="source">The object instance to copy.</param> /// <returns>The copied object.</returns> public static T Clone<T>(T source) { if (!typeof(T).IsSerializable) { throw new ArgumentException("The type must be serializable.", "source"); } // Don't serialize a null object, simply return the default for that object if (Object.ReferenceEquals(source, null)) { return default(T); } IFormatter formatter = new BinaryFormatter(); Stream stream = new MemoryStream(); using (stream) { formatter.Serialize(stream, source); stream.Seek(0, SeekOrigin.Begin); return (T)formatter.Deserialize(stream); } } }
  • 32. public static class ObjectCopier { /// <summary> /// Perform a deep Copy of the object. /// </summary> /// <typeparam name="T">The type of object being copied.</typeparam> /// <param name="source">The object instance to copy.</param> /// <returns>The copied object.</returns> public static T Clone<T>(T source) { if (!typeof(T).IsSerializable) { throw new ArgumentException("The type must be serializable.", "source"); } // Don't serialize a null object, simply return the default for that object if (Object.ReferenceEquals(source, null)) { return default(T); } IFormatter formatter = new BinaryFormatter(); Stream stream = new MemoryStream(); using (stream) { formatter.Serialize(stream, source); stream.Seek(0, SeekOrigin.Begin); return (T)formatter.Deserialize(stream); } } }
  • 33. public static class ObjectCopier { /// <summary> /// Perform a deep Copy of the object. /// </summary> /// <typeparam name="T">The type of object being copied.</typeparam> /// <param name="source">The object instance to copy.</param> /// <returns>The copied object.</returns> public static T Clone<T>(T source) { if (!typeof(T).IsSerializable) { throw new ArgumentException("The type must be serializable.", "source"); } // Don't serialize a null object, simply return the default for that object if (Object.ReferenceEquals(source, null)) { return default(T); } IFormatter formatter = new BinaryFormatter(); Stream stream = new MemoryStream(); using (stream) { formatter.Serialize(stream, source); stream.Seek(0, SeekOrigin.Begin); return (T)formatter.Deserialize(stream); } } }
  • 34. public static class ObjectCopier { /// <summary> /// Perform a deep Copy of the object. /// </summary> /// <typeparam name="T">The type of object being copied.</typeparam> /// <param name="source">The object instance to copy.</param> /// <returns>The copied object.</returns> public static T Clone<T>(T source) { if (!typeof(T).IsSerializable) { throw new ArgumentException("The type must be serializable.", "source"); } // Don't serialize a null object, simply return the default for that object if (Object.ReferenceEquals(source, null)) { return default(T); } IFormatter formatter = new BinaryFormatter(); Stream stream = new MemoryStream(); using (stream) { formatter.Serialize(stream, source); stream.Seek(0, SeekOrigin.Begin); return (T)formatter.Deserialize(stream); } } }
  • 35. public static class ObjectCopier { /// <summary> /// Perform a deep Copy of the object. /// </summary> /// <typeparam name="T">The type of object being copied.</typeparam> /// <param name="source">The object instance to copy.</param> /// <returns>The copied object.</returns> public static T Clone<T>(T source) { if (!typeof(T).IsSerializable) { throw new ArgumentException("The type must be serializable.", "source"); } // Don't serialize a null object, simply return the default for that object if (Object.ReferenceEquals(source, null)) { return default(T); } IFormatter formatter = new BinaryFormatter(); Stream stream = new MemoryStream(); using (stream) { formatter.Serialize(stream, source); stream.Seek(0, SeekOrigin.Begin); return (T)formatter.Deserialize(stream); } } }
  • 36. public static class ObjectCopier { /// <summary> /// Perform a deep Copy of the object. /// </summary> /// <typeparam name="T">The type of object being copied.</typeparam> /// <param name="source">The object instance to copy.</param> /// <returns>The copied object.</returns> public static T Clone<T>(T source) { if (!typeof(T).IsSerializable) { throw new ArgumentException("The type must be serializable.", "source"); } // Don't serialize a null object, simply return the default for that object if (Object.ReferenceEquals(source, null)) { return default(T); } IFormatter formatter = new BinaryFormatter(); Stream stream = new MemoryStream(); using (stream) { formatter.Serialize(stream, source); stream.Seek(0, SeekOrigin.Begin); return (T)formatter.Deserialize(stream); } } }
  • 37. End of Course Go and have some fun and come back for the next Advanced C# Course
  • 38. Take a Look on my other courses @ http://www.slideshare.net/ZGTRZGTR Available courses to the date of this slide: