Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Arrays as Parameters in C#

Tags:

c#

.net

I am trying to create a function that accepts 5 integers, holds them in an array and then passes that array back to the main. I have wrestled with it for a couple of hours and read some MSDN docs on it, but it hasn't "clicked". Can someone please shed some light as to what I am doing wrong? Errors: Not all code paths return a value; something about invalid arguments:

Code:

using System;
using System.IO;
using System.Text;

namespace ANumArrayAPP
{
class Program
{
    static void Main()
    {
        int[] i = new int[5];
        ReadInNum(i);

        for (int a = 0; a < 5; a++)
        {
            Console.Write(a);
        }
    }

    static int ReadInNum(int readIn)
    {
        int[] readInn = new int[5];

        for (int i = 0; i < 5; i++)
        {
            Console.WriteLine("Please enter an interger");
            readInn[i] = Console.Read();
        }
    }
}

}

like image 769
jpavlov Avatar asked Sep 17 '25 10:09

jpavlov


1 Answers

The parameter to ReadInNum is a single int, but you're trying to pass an array. You have to make the parameter match what you're trying to pass in. For example:

static void ReadInNum(int[] readIn)
{
    for (int i = 0; i < readIn.Length; i++)
    {
        Console.WriteLine("Please enter an interger");
        readIn[i] = int.Parse(Console.ReadLine());
    }
}

That will fill the array you pass into the method. Another alternative is to pass in how many integers you want, and return the array from the method:

static int[] ReadInNum(int count)
{
    int[] values = new int[count];
    for (int i = 0; i < count; i++)
    {
        Console.WriteLine("Please enter an interger");
        values[i] = int.Parse(Console.ReadLine());
    }
    return values;
}

You'd call this from Main like this:

int[] input = ReadInNum(5);
for (int a = 0; a < 5; a++)
{
    Console.Write(input[a]);
}
like image 134
Jon Skeet Avatar answered Sep 20 '25 02:09

Jon Skeet