Home > other >  Can I edit multiple array values in one line in C#
Can I edit multiple array values in one line in C#

Time:11-24

So I have some very basic code, and I want to know if it would be better to put it in an array, and if it is possible to edit multiple values of an array in a single line.

My code looks like this, and as you could guess there is a btn_****_Click method for each of those bools. I could obviously do a bool[] whichClick = new bool and then add them all, but is there a shorthand way to edit all 7 bools in a single command? Doesn't do me any good to put it in an array if I'm still stuck using 7 lines to set all 7 bools, in each of the methods.

private void btn_Byte_Click(object sender, EventArgs e)
    {
        byteClick = true;
        shortClick = false;
        intClick = false;
        longClick = false;
        floatClick = false;
        douClick = false;
        decClick = false;
    }
   public void PostProcess(decimal left, decimal right, decimal answer, string oP)
    {
        string outputStr = "";

        // If statements for which data type was selected
        if (byteClick == true)
        {
            try
            {
                byte byteLeft = Decimal.ToByte(left);
                byte byteRight = Decimal.ToByte(right);
                byte byteAnswer = Decimal.ToByte(answer);
                outputStr = $"{byteLeft}{oP}{byteRight}{" = "}{byteAnswer}";
                lbl_Output.Text = outputStr;
            }
            catch (OverflowException) { Error(2); Error(0); }
        }
    }

CodePudding user response:

This could be a good use-case for an Enum.

Define an Enum like so:

public Enum ClickType 
{
    None,
    Byte,
    Short,
    Int,
    Long,
    Float,
    Double,
    Decimal
}

Add a field to the class that contains the event handlers:

private ClickType clickType;

Then, in the event handler, set this field:

private void btn_Byte_Click(object sender, EventArgs e)
{
    this.clickType = ClickType.Byte;
}

And in the postProcess() method, do:

public void PostProcess(decimal left, decimal right, decimal answer, string oP)
{
    ...
    // Or replace this with a switch-case
    if (this.clickType == ClickType.Byte)
    {
        ...
    }
    ...
}

CodePudding user response:

You could write it the following way

    byteClick = true;
    shortClick = intClick = longClick = floatClick = douClick = decClick = false;
  • Related