Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Getter and setter expression for array property

Tags:

c#

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;
        }
    }
}
like image 665
Takeshi Tokugawa YD Avatar asked Apr 11 '26 03:04

Takeshi Tokugawa YD


2 Answers

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; }
}
like image 135
Tim Schmelter Avatar answered Apr 13 '26 15:04

Tim Schmelter


You can write an indexer for your class

public bool this[int index]{
   get { return coolerFanIsOn[index]; }
   set { coolerFanIsOn[index] = value;}
}
like image 36
Transcendent Avatar answered Apr 13 '26 17:04

Transcendent



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!