user1105430
user1105430

Reputation: 1399

C# getter setter default value

How do you set default value for setter getter? I want to do some operations while setting the setter.

public bool spin {
    get { return this.spin; }
    set {
        if (value == false) this.spinBack = true;
        this.spin = value;
    }
}
private bool spinBack;

I tried this on Unity3D and got this error when trying to do so.

StackOverflowException: The requested operation caused a stack overflow.

I tried just setting the getter and leave getter as default like so

public bool spin {
    get;
    set {
        if (value == false) this.spinBack = true;
        this.spin = value;
    }
}
private bool spinBack;

but I get this error

'spin.get' must have a body because it is not marked abstract, extern, or partial

Upvotes: 1

Views: 4544

Answers (1)

Lece
Lece

Reputation: 2377

The StackOverflowException is due to your this.spin = value; line which is recursively setting spin.

Use a backing field instead:

public bool Spin 
{
    get { return _spin; }
    set {
        if (value == false) this.spinBack = true;
        _spin = value;
    }
}

private bool _spin;
private bool spinBack;

Upvotes: 2

Related Questions