Why does an interface allow state declarations in an interface?

According to the answer to Why are we not allowed to specify a constructor in the interface? ,

Because the interface describes the behavior. Constructors are not behavior. How an object is built is an implementation detail.

If interface describes behavior, why does interface allow state declarations?

 public interface IStateBag { object State { get; } } 
+4
source share
4 answers

Well, thatโ€™s not entirely true. If the interfaces let you declare the fields, this will be the state. Since the property is just syntactic sugar for the get and set methods, this is allowed.

Here is an example:

 interface IFoo { Object Foo { get; set; } } 

The previous interface compiles to the following IL:

 .class private interface abstract auto ansi IFoo { .property instance object Foo { .get instance object IFoo::get_Foo() .set instance void IFoo::set_Foo(object) } } 

As you can see, even the interface sees the property as methods.

+11
source

The property is not an implementation. For example, you cannot define fields. Properties and events are really just special method templates; with the property "get_" and "set_", as well as with the event "add_" and "remove _".

So this is just a method.

+9
source

A A property is also a description of behavior: a class that implements an interface still has complete freedom in deciding how to implement properties.

The inability to declare properties in the interface will force developers to create getters and setters themselves:

 object GetState(); void SetState( object o ); 
+2
source

If the interface describes the behavior, why does the interface allow state declarations?

State is a type of behavior. There is nothing wrong with the fact that the interface defines the state as one of the actions.

I believe your question is based on a false argument. I think you accept this quote too lyrically. I think a clearer way of saying this is that ...

Interfaces describe the behavior of a specific object. Constructors are a method of creating an object.

+1
source

All Articles