Exclusive Clothing Sale On Flipkart

Get up to 50% off on our latest collection.

Shop Now

Prototype Design Pattern in C# with Examples

In this article, we are going to discuss prototype design patterns in C#.

prototype design patterns are the creational design pattern.

As per the Gang of Four Definition: "Prototype Design Pattern Specify the kind of objects to create using a prototypical instance, and create new objects by copying this prototype"

As per the prototype design pattern, we need to create an object once and can use it across the application, creating an object again and again in an application is an expensive and time-consuming task so as per this pattern once we create an object, we can utilize it wherever we need it.

  • reducing the complexity of the application to create the objects.
  • reduce the need to creating of an object again and again.
  • We can remove the object in runtime.

Prototype Design Pattern in C# 

below is an example of creating a prototype design pattern using the shallow copy method. here we are using the inbuild ICloneable interface.

public class Student: ICloneable
{
    public string Name { get; set; }
    public string Address { get; set; }
    public int Age { get; set; }
    public string Gender { get; set; }
    public object Clone()
    {
        return this.MemberwiseClone();
    }
 
}
public class ProtoTypeDesignPattern
{
    static void Main(string[] args)
    {
        Student _student = new Student
        {
            Name = "dotnetOffice",
            Address = "XYZ",
            Age = 10,
            Gender = "Male"
        };

        Console.WriteLine($"Student Name:  {_student.Name}");

        Student cloneName = _student.Clone() as Student;
        Console.WriteLine($"Cloned Name:  {_student.Name}");

        cloneName.Name = "other name";
        Console.WriteLine($"origional name - {_student.Name}");
        Console.WriteLine($"Cloned Name - {cloneName.Name}");
    }
}

 

Share this

Related Posts

Previous
Next Post »

Exclusive Clothing Sale On Flipkart

Get up to 50% off on our latest collection.

Shop Now