Ralph Tandetzky
Ralph Tandetzky

Reputation: 23610

Why use @property in D?

I figured out by trying that

struct PropertyTest
{
    @property int x() { return val; }
    @property void x( int newVal ) { val = newVal; }

    void test()
    {
        int j;
        j = x;
        x = 5;
    }

private:
    int val;
}

does exactly the same when I leave the @property out. Everything compiles fine. What's the point then for declaring functions as @property?

BTW, I'm using the dmd2 compiler.

Upvotes: 7

Views: 477

Answers (2)

eco
eco

Reputation: 2229

The reason they work without @property is because @property was added after they allowed the property method syntax. Adding -property to your DMD command line enforces use of @property annotation. It's not the default for backward compatibility reasons. Someday it will become the default (or so they say) so it's best to compile with -property to ensure you are annotating properly.

Upvotes: 9

user541686
user541686

Reputation: 210445

It lets you use a no-arg method without parentheses (like reading a variable), and it lets you call a single-arg method without parentheses, the way you assign to a variable.

@property int foo() { ... }
@property void bar(int x) { ... }

void main()
{
    bar = foo;
}

You should specify -property as a command line option for the compiler.

Upvotes: 1

Related Questions