Takeshi Tokugawa YD
Takeshi Tokugawa YD

Reputation: 923

C#: Getter and setter expression for array property

How can I write the getter and setter expression for array property CoolerFanIsOn in the class CoolerSystem? I showed the similar desired expression for non-array property IsOn of Lamp class.

class CoolerFan{

    bool isOn;
    public bool IsOn {
        get => isOn;
        set {
            isOn = value;
        }
    }
}

class CoolerSystem {

    private CoolerFan[] = new CoolerFan[5];
    private bool[] coolerFanIsOn = new Boolean[5];

    // invalid code from now

    public bool[] CoolerFanIsOn {
        get => coolerFanIsOn[number];
        set {
            coolerFanIsOn[number] = value;
        }
    }
}

Upvotes: 3

Views: 7577

Answers (3)

Tim Schmelter
Tim Schmelter

Reputation: 460108

You can use indexer:

public class CoolerSystem
{
    private bool[] _coolerFanIsOn = new Boolean[5];

    public bool this[int index]
    {
        get => _coolerFanIsOn[index];
        set => _coolerFanIsOn[index] = value;
    }
}

Btw, the => are expression bodied properties which were new in C#6. If you can't use (setter was new in C#7) use the old syntax, indexers have nothing to do with it(C#3):

public bool this[int index]
{
    get { return _coolerFanIsOn[index];  }
    set { _coolerFanIsOn[index] = value; }
}

Upvotes: 7

Transcendent
Transcendent

Reputation: 5755

You can write an indexer for your class

public bool this[int index]{
   get { return coolerFanIsOn[index]; }
   set { coolerFanIsOn[index] = value;}
}

Upvotes: 2

Felix D.
Felix D.

Reputation: 5093

Maybe this is what you would like to do:

class CoolerSystem
{

    private CoolerFan[] _fans = new CoolerFan[5];

    private bool[] _coolerfanIsOn;

    public bool[] CoolerFanIsOn
    {
        get { return _coolerfanIsOn; }
        set
        {
            _coolerfanIsOn = value;
        }
    }

    public bool GetFanState(int number)
    {
        return CoolerFanIsOn[number];
    }

    public void SetFanState(int number, bool value)
    {
        CoolerFanIsOn[number] = value;
    }
}

Upvotes: 0

Related Questions