Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does interface allow declaring states in interface?

Tags:

.net

interface

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; }
}
like image 759
dance2die Avatar asked Nov 29 '22 20:11

dance2die


1 Answers

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.

like image 122
Andrew Hare Avatar answered Dec 04 '22 16:12

Andrew Hare