vote up 3 vote down star

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; }
}
flag

4 Answers

vote up 8 vote down check

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.

link|flag
vote up 9 vote down

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.

link|flag
vote up 1 vote down

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 );
link|flag
vote up 1 vote down

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.

link|flag

Your Answer

Get an OpenID
or

Not the answer you're looking for? Browse other questions tagged or ask your own question.