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:
-
I have read that
System.Array
class is derived fromSystem.Object
. But why is this not seen in the above definition? -
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
System.Array
is effectively derived fromSystem.Object
. You don't see it here, because everything in .NET Framework derives by default fromSystem.Object
, including types likeint
(System.Int32
).In other words:
class MyClass : MyOtherClass { }
indicates thatMyClass
is derived fromMyOtherClass
.class MyClass { }
indicates thatMyClass
is derived fromSystem.Object
.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:
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 typestring
calledName
which has a getter.The actual type may be a
Person
. Or aCat : Animal
. Or anAircraftModel
.SayHello
accepts them all, at the condition for them to implementINamed
.Why would
Person
implement an interface, instead of simply containing theName
property?Because, aside using Reflection or dynamic programming, the caller doesn't have a clue that
Person
effectively implementsName
property. For example this code will not compile: