Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic C# Copy Constructor

What would be the best way to write a generic copy constructor function for my c# classes? They all inherit from an abstract base class so I could use reflection to map the properties, but I'm wondering if there's a better way?

like image 823
lomaxx Avatar asked Jan 11 '09 22:01

lomaxx


People also ask

What is generic C?

Advertisements. Generics allow you to define the specification of the data type of programming elements in a class or a method, until it is actually used in the program. In other words, generics allow you to write a class or method that can work with any data type.

Are there generic types in C?

It allows efficient development without the need to incorporate or switch to C++ or languages with builtin template systems, if desired. Using generics and templates in C can also make programs more type safe, and prevent improper access of memory.

What is generic program in C++?

Generic Programming enables the programmer to write a general algorithm which will work with all data types. It eliminates the need to create different algorithms if the data type is an integer, string or a character. Once written it can be used for multiple times and cases.


2 Answers

A copy constructor basically means you have a single parameter, which is the object you're going to copy.

Also, do a deep copy, not a shallow copy.

If you don't know what deep and shallow copies are, then here's the deal:

Suppose you're copying a class that has a single row of integers as field.

A shallow copy would be:

public class Myclass()
{
    private int[] row;
    public MyClass(MyClass class)
    {
        this.row = class.row
    }
}

deep copy is:

public class Myclass()
{
    private int[] row;
    public MyClass(MyClass class)
    {
        for(int i = 0; i<class.row.Length;i++)
        {
            this.row[i] = class.row[i];
        }
    }
}

A deep copy really gets the actuall values and puts them in a new field of the new object, whilst a shallow copy only copies the pointers.

With the shallow copy, if you set:

row[3] = 5;

And then print both rows, both prints will have 5 as value of the 4th number. With a deep copy however, only the first print will have this, since the rows don't have the same pointers.

like image 87
Vordreller Avatar answered Sep 18 '22 16:09

Vordreller


Avoid reflection if you can. Each class should have the responsibility of copying its own properties, and send it further to the base method.

like image 32
Øyvind Skaar Avatar answered Sep 21 '22 16:09

Øyvind Skaar