The Prototype Pattern is used when the cost of creating a brand-new object from scratch is too high (e.g., it requires a database query or a 3-second network call). Instead of doing the work again, you simply "Clone" an existing object that you've already created.
If you object contains a list of other objects, a Shallow Clone just copies the memory address (both objects share the list). A Deep Clone copies everything, including the nested items.
public class User : ICloneable
{
public string Name { get; set; }
public object Clone()
{
// MemberwiseClone is a Shallow Clone built into .NET
return (User)this.MemberwiseClone();
}
}
In modern C#, you should avoid ICloneable (as it returns object and requires casting). Instead, define a strongly-typed Clone() method or use a Copy Constructor.
Q: "How does the C# 'Record' type implement the Prototype pattern?"
Architect Answer: "The `with` keyword in C# Records is a specialized compiler-implemented version of the Prototype pattern. When you write `var newUser = oldUser with { Age = 30 };`, the compiler internally clones the record (Prototype) and only changes the specified property. This ensures absolute immutability while making 'Cloning' feel like a first-class language feature."