
- C# Basic Tutorial
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Decision Making
- C# - Loops
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
- C# Useful Resources
- C# - Questions and Answers
- C# - Quick Guide
- C# - Useful Resources
- C# - Discussion
What is a copy constructor in C#?
Copy Constructor creates an object by copying variables from another object.
Let us see an example −
Example
using System; namespace Demo { class Student { private string name; private int rank; public Student(Student s) { name = s.name; rank = s.rank; } public Student(string name, int rank) { this.name = name; this.rank = rank; } public string Display { get { return " Student " + name +" got Rank "+ rank.ToString(); } } } class StudentInfo { static void Main() { Student s1 = new Student("Jack", 2); // copy constructor Student s2 = new Student(s1); // display Console.WriteLine(s2.Display); Console.ReadLine(); } } }
Above we saw, firstly we declared a copy constructor −
public Student(Student s)
Then a new object is created for the Student class −
Student s1 = new Student("Jack", 2);
Now, the s1 object is copied to a new object s2 −
Student s2 = new Student(s1);
This is what we call copy constructor.
- Related Articles
- Copy Constructor in C++
- When is copy constructor called in C++?
- Java copy constructor
- Why do we need a copy constructor and when should we use a copy constructor in Java?
- Virtual Copy Constructor in C++
- Copy constructor vs assignment operator in C++
- What is a constructor in Java?
- Difference Between Copy Constructor and Assignment Operator in C++
- What's the difference between assignment operator and copy constructor in C++?
- What is a constructor method in JavaScript?
- What is a default constructor in JavaScript?
- What is a static constructor in C#?
- What is a parameterized constructor in C# programs?
- What is converting constructor in C++ ?
- What is constructor overloading in Java?

Advertisements