What are the interfaces implemented by Array class in C#?


System.Array implements interfaces, like ICloneable, IList, ICollection, and IEnumerable, etc. The ICloneable interface creates a copy of the existing object i.e a clone.

Let us see learn about the ICloneable interface. It only has a Clone() methods because it creates a new object that is a copy of the current instance.

The following is an example showing how to perform cloning using ICloneable interface −

Example

using System;

class Car : ICloneable {
   int width;

   public Car(int width) {
      this.width = width;
   }

   public object Clone() {
      return new Car(this.width);
   }

   public override string ToString() {
      return string.Format("Width of car = {0}",this.width);
   }
}

class Program {
   static void Main() {
      Car carOne = new Car(1695);
      Car carTwo = carOne.Clone() as Car;

      Console.WriteLine("{0}mm", carOne);
      Console.WriteLine("{0}mm", carTwo);
   }
}

Let us now see how to use Array.Clone in C# to clone an array −

Example

using System;

class Program {
   static void Main() {
      string[] arr = { "one", "two", "three", "four", "five" };
      string[] arrCloned = arr.Clone() as string[];

      Console.WriteLine(string.Join(",", arr));

      // cloned array
      Console.WriteLine(string.Join(",", arrCloned));
      Console.WriteLine();
   }
}

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 21-Jun-2020

713 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements