I have an interface and two classes which implement it. I'm getting a compiler error, and I'm not quite sure why.
interface IPerson
{
ICollection<string> NickNames{get;set;}
}
class ObservablePerson : IPerson
{
ObservableCollection<string> NickNames{get;set;}
}
class ListPerson : IPerson
{
List<string> NickNames{get;set;}
}
I'm having a bit of trouble understanding why this won't work, as List and ObservableCollection both implement ICollection.
Like a class, Interface can have methods, properties, events, and indexers as its members. But interfaces will contain only the declaration of the members. The implementation of the interface's members will be given by class who implements the interface implicitly or explicitly.
The Interface is a medium to interact between user and system devices. For example, in our real life, if we consider the interface to be given as an example is the air condition, bike, ATM machine, etc.
You just specify that there is a property with a getter and a setter, whatever they will do. In the class, you actually implement them. The shortest way to do this is using this { get; set; } syntax. The compiler will create a field and generate the getter and setter implementation for it.
Interface attributes are by default public , static and final. An interface cannot contain a constructor (as it cannot be used to create objects)
I'm having a bit of trouble understanding why this won't work, as List and ObservableCollection both implement ICollection.
Yes, but the interface states that an ICollection<string>
is returned. The underlying type may be an ObservableCollection<string>
or a List<string>
, but the signature needs to conform to the interface. An ObservableCollection<string>
is an ICollection<string>
, but an ICollection<string>
is not necessarily an ObservableCollection<string>
.
Also, your methods need to be public (they are currently private). Interfaces don't deal with private or protected methods, it defines the public interface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With