Cloneable objects

0
In C#, the ICloneable interface is used to create cloneable objects. The ICloneable interface contains a single method named Clone() that returns a new object that is a copy of the original object. The return type of Clone() is System.Object, so it is necessary to cast the result to the appropriate type.

Here is an example of a class that implements ICloneable:

public class MyClass : ICloneable
{
    public int MyProperty { get; set; }

    public object Clone()
    {
        return new MyClass { MyProperty = this.MyProperty };
    }
}

This class has a single property named MyProperty, and implements the Clone() method by creating a new instance of the class and copying the value of MyProperty to the new object.

To create a clone of an object that implements ICloneable, you can call the Clone() method on the object, like this:

var original = new MyClass { MyProperty = 42 };

var clone = (MyClass)original.Clone();


In this example, a new instance of MyClass is created with MyProperty set to 42. The Clone() method is then called on the original object, and the result is cast to MyClass to create a new instance of the class that is a copy of the original.

It's worth noting that the Clone() method creates a shallow copy of the object, which means that any reference types contained within the object are not cloned, but are instead copied by reference. If you need to create a deep copy of an object, you will need to implement custom logic to clone any reference types contained within the object as well.


Tags

Post a Comment

0Comments
Post a Comment (0)