Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interfaces and properties

Is it possible to declare a property in an interface without declaring the get- and set-methods for it? Something like:

IValue = interface   property value: double; end; 

I want to state that the implementor should have a property called value, returning a double, but I really don't care if it returns a private field or the result from a function.

If it is possible, is it possible to declare it read/write or read-only?

like image 872
Vegar Avatar asked Aug 11 '09 13:08

Vegar


People also ask

What are the properties of an interface?

The byte code of an interface appears in a . All of the methods in an interface are abstract. An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final. An interface is not extended by a class; it is implemented by a class.

Do interfaces have properties?

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.

Can I define a property in interface?

Beginning with C# 8.0, an interface may define a default implementation for members, including properties. Defining a default implementation for a property in an interface is rare because interfaces may not define instance data fields.

Should interfaces 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.


1 Answers

No. Interfaces are implemented as function tables (basically a simple virtual method table) and the compiler needs to know there's a function to map the property onto. You can declare a property on an interface, but it has to have functions as getter/setter values, not fields. You can make it read-only or write-only, though.

like image 150
Mason Wheeler Avatar answered Nov 09 '22 11:11

Mason Wheeler