Created
November 15, 2012 07:56
-
-
Save codewithpassion/4077292 to your computer and use it in GitHub Desktop.
A better clonable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Book : ICloneable | |
{ | |
public string Title { get; set; } | |
public String Description { get; set; } | |
object ICloneable.Clone() | |
{ | |
return new Book { Title = Title , Description = Description }; | |
} | |
} | |
public class Client | |
{ | |
public void Do() | |
{ | |
Book myBook = new Book { Title = "Clone Wars", Description = "A book full of clones!" }; | |
Book cloneBook = myBook.Clone(); | |
// ... | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface ICloneable<T> | |
{ | |
T Clone(); | |
} | |
public static class CloneableExtension | |
{ | |
public static T Clone<T>(this T obj) where T : ICloneable | |
{ | |
if (obj == null) | |
return default(T); | |
return (T)obj.Clone(); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment