COPY CONSTRUCTOR
A copy constructor is an instance constructor which takes object of the class as parameter. A copy constructor is therefore, a parameterized instance constructor which parameter is the object of the class of the constructor (or, we can say that its parameter type is its class).
using System;
namespace ConsoleCopyConstructor
{
class Student
{
public int Id { get; set; }
public string Name { get; set; }
//parameterized
constructor
public Student(int id, string name)
{
this.Id = id;
this.Name = name;
}
//copy
constructor
public Student(Student s)
{
this.Id = s.Id;
this.Name = s.Name;
}
public void
StudentDetails()
{
Console.WriteLine("Id:{0}, Name:{1}", Id, Name);
}
}
class Program
{
static void Main(string[] args)
{
Student s1 = new Student(1, "Ajeet");
Student s2 = new Student(s1);
Console.WriteLine("s2 is copy of s1");
s1.StudentDetails();
s2.StudentDetails();
Console.WriteLine("\nChange the s2 data:");
s2.Id = 2;
s2.Name = "Ravi";
s1.StudentDetails();
s2.StudentDetails();
Console.ReadKey();
}
}
}
No comments:
Post a Comment