As a spinoff from my other thread on overriding non-virtual methods, Ive been doing some work with interfaces and Im confused about interfaces in C#.
Specifically, I am creating a collection class, MyCollection, that inherits Collections.CollectionBase and IList. MyCollection will store only objects of type MyItem. Therefore, I have:
And it works just fine. What I am confusted about is that this class implements the IList interface which defines, among other methods:
public int Add(object item);
Because the signature of my Add method is not the same as the signature of ILists Add method, (not to mention the fact that I have not yet bothered to implement some of the other IList methods) I would expect to get compile errors because I have not faithfully implemented the IList interface.
For example, if I define:
And then modify my collection class to implement IMine:
public class MyCollection : Collections.CollectionBase, IList, IMine
And change nothing else in my class, I will get compile errors becase I did not implement either the Add(object item) or the MyValue members.
So why is the IList interface different from the IMine interface? Why does the compiler enforce IMine, but give me flexability in IList? I hope someone can explain this to me.
Thanks.
Specifically, I am creating a collection class, MyCollection, that inherits Collections.CollectionBase and IList. MyCollection will store only objects of type MyItem. Therefore, I have:
Code:
public class MyCollection : Collections.CollectionBase, IList
{
// stuff
public int Add(MyItem item)
{
return List.Add(item);
}
// more stuff
}
And it works just fine. What I am confusted about is that this class implements the IList interface which defines, among other methods:
public int Add(object item);
Because the signature of my Add method is not the same as the signature of ILists Add method, (not to mention the fact that I have not yet bothered to implement some of the other IList methods) I would expect to get compile errors because I have not faithfully implemented the IList interface.
For example, if I define:
Code:
public interface IMine
{
// Method
int Add(object item);
// Property
int MyValue
{
get;
}
}
And then modify my collection class to implement IMine:
public class MyCollection : Collections.CollectionBase, IList, IMine
And change nothing else in my class, I will get compile errors becase I did not implement either the Add(object item) or the MyValue members.
So why is the IList interface different from the IMine interface? Why does the compiler enforce IMine, but give me flexability in IList? I hope someone can explain this to me.
Thanks.