What is a copy constructor and when should it be used in C #?

In fact, I did not understand the concept of this, which means why and when it should be used. Usually we can assign values ​​to an instance of a class, but why should we send an object to another object like this:

    private void button8_Click(object sender, EventArgs e)
    {
        rectangle r1 = new rectangle(50, 70);
        rectangle r2 = new rectangle(r1);
    }



class rectangle
{
    private int length;
    private int breadth;


    public rectangle(rectangle x)
    {
        length = x.length;
        breadth = x.breadth;
        MessageBox.Show("I'm a Copy Constructor. \n Length= " + length.ToString() + "\n breadth= " + breadth.ToString());

    }
}
+4
source share
2 answers

This is a possible approach for fully or partially initializing an object that copies the values ​​of elements from the original object.

In your case, you can call this as matching objects.

rectangle CreateFrom, , factory:

class rectangle
{
    private int length;
    private int breadth;

    public static rectangle CreateFrom(rectangle x)
    {
        rectangle r = new rectangle();
        r.length = x.length;
        r.breadth = x.breadth;

        return r;
    }
}

... , , :

private void button8_Click(object sender, EventArgs e)
{
    rectangle r1 = new rectangle(50, 70);
    rectangle r2 = rectangle.CreateFrom(r1);
}
+1

- C++: . , C++ ( ), . : . , .

: C++ . , , .

, C# . C#. . , .

: structs , . , .

++ . 12.8, 288 ++ 14.

+1

All Articles