Programming Tips oops: Copy constructors

Source: Internet
Author: User
Tags constant constructor copy reference variable

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.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.