DekGenius.com
Team LiB   Previous Section   Next Section

8.5 Copy Constructors

A copy constructor creates a new object by copying variables from an existing object of the same type. For example, you might want to pass a Time object to a Time constructor so that the new Time object has the same values as the old one.

C# does not provide a copy constructor, so if you want one you must provide it yourself. Such a constructor copies the elements from the original object into the new one:

public Time(Time existingTimeObject)
{
    year = existingTimeObject.year;
    month = existingTimeObject.month;
    date = existingTimeObject.date;
    hour = existingTimeObject.hour;
    minute = existingTimeObject.minute;
    second = existingTimeObject.second;
}

A copy constructor is invoked by instantiating an object of type Time and passing it the name of the Time object to be copied:

Time newCopy = new Time(existingTimeObject);

Here an existing Time object (existingTimeObject) is passed as a parameter to the copy constructor which will create a new Time object (newCopy).

    Team LiB   Previous Section   Next Section