okr okr - 27 days ago 182
C# Question

"Not all code paths return a value"

I'm working with arrays and methods. I'm working on writing a code that will calculate the average of numbers entered by user in an array. I came up with the first method but VS tells me that "not all code paths return a value". When I tested the code in the Main() method it works well but when it's inside my GetValues() method i get the error.

I read all other posts but they not quite make sense to me because of their specificity. I know this isn't too difficult but I'm a beginner and trying to understand this myself.

My program isn't done yet, the following code is just the first part (method) of my program. Once GetValues () work, the idea is then to call this method from another method that will calculate the average. Again, GetValues() is supposed to capture the array.

Here's the code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace testscores
{
class Program
{
static void Main(string[] args)
{
}

private static int[] GetValues()
{

string inValue;
int[] score = new int[5];
int total = 0;

for (int i = 0; i < score.Length; i++)
{
Console.Write("Enter Score {0}: ", i + 1);
inValue = Console.ReadLine();
score[i] = Convert.ToInt32(inValue);
}

for (int i = 0; i < score.Length; i++)
{
total += score[i];
}
}
}
}

Answer Source

Are you trying to return the integer array score?

   ....
        for (int i = 0; i < score.Length; i++)
        {
            total += score[i];
        }
        return score;
    }

So you can capture this array when you call it like so

int[] scores = GetValues();