Interfaces, as defined by MSDN "contain only the signatures of methods, delegates or events." However, since properties are no more than syntactic sugar for a get and set method, they are also allowed in interfaces. My question is - is there any situation where defining properties in an interface is appropriate or should we stick to the scenarios described by MSDN?
+17
A:
I think properties are perfectly acceptable in interfaces.
As you said, they really are a get, set, or get and set method. Many interfaces in the Framework define properties, such as IAsyncResult and IWebProxy.
Reed Copsey
2010-03-21 23:30:42
Thank you, Reed. In this case, should these properties be of elementary (non user defined) types? The reason I ask is because if you for example define it as a domain type, you may end up with a circular reference.
Otávio Décio
2010-03-21 23:37:24
@Otávio Décio: Keep in mind the purpose of an interface. An interface defines a contract. If a property is required for the contract, then it's fine. You shouldn't end up with circular references, since the properties shouldn't be types that are directly implementing the interface, but rather either basic, framework types, or types that, themselves, form part of the "contract". IWebProxy (linked above) is a good example - it has a Credentials property, which is of ICredentials. That's part of the contract, but essential a "user defined" type still (for that lib).
Reed Copsey
2010-03-21 23:40:00
@Reed - just to make sure - properties defined in interfaces should either be non user defined concrete types or interface types (user defined or not).
Otávio Décio
2010-03-21 23:43:14
@Otávio Décio: I don't have a problem with user defined concrete types, either - but I think care needs to be maintained in this case...
Reed Copsey
2010-03-21 23:57:05
+5
A:
The article you link to also states:
An interface can be a member of a namespace or a class and can contain signatures of the following members:
- Methods
- Properties
- Indexers
- Events
Simon Bartlett
2010-03-21 23:33:03
A:
Yes, An interface should define properties when it really in need. Please suppose that. There is a IUser interface that has defined a property "Name" then you can use it without worry about if the object didn't implement the property.
public void main()
{
IUser u = User.GetUser("id");
string name = u.Name;
}
Millionbonus
2010-03-22 02:00:51