tags:

views:

218

answers:

4

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

Because an interface describes behaviour. Constructors aren't behaviour. How an object is built is an implementation detail.

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

public interface IStateBag
{
    object State { get; }
}
+8  A: 

A property is not the implementation. For example, you can't define fields. Properties and events are actually just special patterns of methods; with a property it is "get_" and "set_", and with an event "add_" and "remove_".

So this is just a method.

Marc Gravell
+9  A: 

Well - its not really state. If interfaces allowed you to declare fields then that would be state. Since a property is just syntax sugar for get and set methods it is allowed.

Here is an example:

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

The previous interface gets compiled 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.

Andrew Hare
+1  A: 

A Property is also a description of behaviour: A class implementing the interface still has total freedom in deciding how to implement the properties.

Not allowing properties to be declared in an interface would only force developers to create getters and setters manually:

object GetState();
void SetState( object o );
Lennaert
+1  A: 

If interface describe behavior, why does interface allow declaring state?

State is a type of behavior. There is nothing wrong with an interface specifying state as one of the behavior.

I believe your question is predicated on a false argument. I think you're taking that quote a bit too literraly. I think a clearer way of saying this is that ...

Interfaces describe behavior a particular object posses. Constructors are a method of creating an object.

JaredPar