C sharp - Copy Constructor in C#
What is a Copy Constructor?
A copy constructor is a constructor that creates a new object by copying the values from an existing object of the same class.
It is useful when you want to duplicate an object with the same data.
Syntax
class ClassName
{
public ClassName(ClassName obj)
{
// Copy values from obj to the new object
}
}
Simple Example
using System;
class Book
{
public string title;
public int pages;
// Parameterized constructor
public Book(string t, int p)
{
title = t;
pages = p;
}
// Copy constructor
public Book(Book b)
{
title = b.title;
pages = b.pages;
}
public void Display()
{
Console.WriteLine("Title: " + title);
Console.WriteLine("Pages: " + pages);
}
}
class Program
{
static void Main()
{
// Create original object
Book book1 = new Book("C# Basics", 300);
// Create copy using copy constructor
Book book2 = new Book(book1);
book2.Display();
}
}
Output:
Title: C# Basics
Pages: 300