Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should interfaces define properties?

Tags:

c#

interface

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?

like image 992
Otávio Décio Avatar asked Mar 21 '10 23:03

Otávio Décio


People also ask

Can an interface define properties?

An interface can contain declarations of methods, properties, indexers, and events. However, it cannot contain fields, auto-implemented properties.

Should an interface have properties?

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.

Can we have properties in interface?

On implementation of an interface, you must override all of its methods. Interfaces can contain properties and methods, but not fields/variables. Interface members are by default abstract and public. An interface cannot contain a constructor (as it cannot be used to create objects)

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)


2 Answers

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.

like image 56
Reed Copsey Avatar answered Sep 22 '22 15:09

Reed Copsey


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
like image 31
Simon Bartlett Avatar answered Sep 19 '22 15:09

Simon Bartlett