Trying to pass an array into a method

357mag

Well-known member
Joined
Mar 31, 2023
Messages
58
Programming Experience
3-5
I have a program I did in Java and I'm trying to do it in C#. Visual Studio is flagging a lot at the bottom. Where I declare and define the method at the bottom. I want my method to receive the numbers array and then multiply each element by 2 and then send that result back into the main program.

But I almost think I got the code in the wrong spot, I don't know.
C#:
 private void buttonShowModifiedValues_Click(object sender, EventArgs e)
        {
            int[] numbers = { 2, 4, 5, 6, 8 };
            int[] newArray;

            newArray = modifyNumbers(numbers);
        }

        private void FormPassArrayToMethod_Load(object sender, EventArgs e)
        {
            int[] numbers = { 2, 4, 5, 6, 8 };

            for (int i = 0; i < numbers.Length; i++)
                textBoxOriginalArrayValues.Text = textBoxOriginalArrayValues.Text + numbers[i] + " ";
        }
        public static int[] modifyNumbers(int[] modifiedNumbers)

            for(int i = 0; i<modifiedNumbers.Length; i++)
                modifiedNumbers[i] *= 2;
            
            return modifiedNumbers;
 
I got rid of all the red, squiggly lines. I put in braces so that problem looks solved. But when I click on the Show Modified Values button, my program doesn't show anything in the textbox. I'll keep digging around.
 
Okay I found the problem. I was missing a loop to print the new array in the textbox. I don't quite understand why I needed to add braces around my method definition though.
 
C# is not Python which uses indents to denote scopes. C# (and Java) need braces around method bodies (unless you use expression bodied methods).
 
I don't quite understand why I needed to add braces around my method definition though.

C# language spec says so. That's fairly inviolable I'm afraid. Methods typically look like:

C#:
returntype MethodName(argtype arg1, argtype arg2..){
  multi;
  line;
  body;
}

returntype MethodName(argtype arg1, argtype arg2..) => singleline body;

Note the uppercase letter at the start of the name
 
Back
Top Bottom