Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interface as a Property

Tags:

c#

.net

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 image 482
user582181 Avatar asked Jan 19 '11 22:01

user582181


People also ask

CAN interface have a property?

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.

What is example of interface in real life?

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.

How do you initialize an interface property?

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.

CAN interface have properties Java?

Interface attributes are by default public , static and final. An interface cannot contain a constructor (as it cannot be used to create objects)


1 Answers

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.

like image 51
Ed S. Avatar answered Oct 13 '22 13:10

Ed S.