OOPs
1. What is a copy constructor
We know that constructors are a special way to initialize the instance that we want to create. Usually we want to assign an instance to another variable C # just assign the reference to the new variable is essentially a reference to the same variable, so how can we assign a value while creating a whole new variable instead of just assigning the instance reference? We can use the copy constructor.
we can create a constructor for a class that uses only one parameter of that type, such as:
Public Student (Student Student)
{
THIS.name = Student.name;
}
using the constructor above, we can copy a new instance value instead of assigning an instance of the same reference.
Class Student
{
private string name;
Public Student (string name)
{
THIS.name = name;
}
Public Student (Student Student)
{
THIS.name = Student.name;
}
public string Name
{
Get
{
return name;
}
Set
{
name = value;
}
}
}
Class Final
{
static void Main ()
{
Student Student = new Student ("A");
Student newstudent = new Student (Student);
Student. Name = "B";
System.Console.WriteLine ("The new student ' s name is {0}", newstudent.name);
}
}
The new student ' s name is A.
2. What is a read-only constant
is a static, read-only variable that is usually assigned a value in a static constructor.
Class Numbers
{
public ReadOnly int m;
public static readonly int n;
public Numbers (int x)
{
M=x;
}
Static Numbers ()
{
n=100;
}
//where n is a read-only constant, there is only one value for all instances of the class, and M is different depending on the instance.