System.Int32[] hides IList implemetation? How?

  • Thread starter Thread starter tsteinke
  • Start date Start date
T

tsteinke

I noticed somthing. The native Array Types implement the IList
interface. However they do not contain all the methods in the
interfaces they implement. for example...

int[] test=new int[100];
test.Add(5); <<<< This is a Compile Error

However

if(test is IList)
{
IList list=test;
list.Add(123);
}

Comiles Just fine and causes a runtime exception when Add is called.

How is this possible?! Is there a way to hide methods of an interface
when you implement it?

Thomas
 
When you implement a method of an interface you have two options:
public int Add(object value) {} // Makes the method part of your class
(implicit)
int IList.Add(object value) {} // Method only accessible through the
interface (explicit)

Note that someone can still call the explicit method by casting your class
to the interface type:
int[] test=new int[100];
IList testList = (IList) test;
testList.Add(5);
 
Makes Sense. Thank you very much.

Sean said:
When you implement a method of an interface you have two options:
public int Add(object value) {} // Makes the method part of your class
(implicit)
int IList.Add(object value) {} // Method only accessible through the
interface (explicit)

Note that someone can still call the explicit method by casting your class
to the interface type:
int[] test=new int[100];
IList testList = (IList) test;
testList.Add(5);

I noticed somthing. The native Array Types implement the IList
interface. However they do not contain all the methods in the
interfaces they implement. for example...

int[] test=new int[100];
test.Add(5); <<<< This is a Compile Error

However

if(test is IList)
{
IList list=test;
list.Add(123);
}

Comiles Just fine and causes a runtime exception when Add is called.

How is this possible?! Is there a way to hide methods of an interface
when you implement it?

Thomas
 
Back
Top