C# Array Class – Implementation Questions

arraycnet

I am studying the Array class in C#. The following is the implementation of System.Array class:

[SerializableAttribute] 
[ComVisibleAttribute(true)] 
public abstract class Array : ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable 

I have two questions regarding this:

  1. I have read that System.Array class is derived from System.Object. But why is this not seen in the above definition?

  2. ICloneable is implemented in order to allow the Array to be Deep-Copied in case of XML serialization. ICloneable provides only one method – Clone(). What is the advantage of implementing ICloneable explicitly? Why could not Clone() method be directly implemented? Is this a type of providing a Marking Interface pattern where a particular Interface is implemented only to convey a certain characteristic of the class?

Best Answer

  1. System.Array is effectively derived from System.Object. You don't see it here, because everything in .NET Framework derives by default from System.Object, including types like int (System.Int32).

    In other words:

    • class MyClass : MyOtherClass { } indicates that MyClass is derived from MyOtherClass.

    • class MyClass { } indicates that MyClass is derived from System.Object.

  2. The advantage of using an interface is that methods (or classes with generics) may rely on interfaces when they need a specific method or property. Imagine the following source code:

    public interface INamed
    {
        string Name { get; }
    }
    
    public void SayHello(INamed namedEntity)
    {
        Console.WriteLine("Hello, " + namedEntity.Name + "!");
    }
    

    By using an interface, the method shows that it doesn't care about the exact type of namedEntity. All what it cares about is that the object should contain a property of type string called Name which has a getter.

    The actual type may be a Person. Or a Cat : Animal. Or an AircraftModel. SayHello accepts them all, at the condition for them to implement INamed.

    Why would Person implement an interface, instead of simply containing the Name property?

    Because, aside using Reflection or dynamic programming, the caller doesn't have a clue that Person effectively implements Name property. For example this code will not compile:

    public class Person
    {
        public string Name { get; set; }
    }
    
    public void SayHello(object namedEntity)
    {
        Console.WriteLine("Hello, " + namedEntity.Name + "!"); // Compile-time error here
    }
    
    public void Main()
    {
        this.SayHello(new Person { Name = "Robert" });
    }