Q:

function return value, not all code paths return

hi I have code like this
Global.dbCon.Open();
List<int> idQuestions = new List<int>();
kalimatSql = kalimatSql;
Global.reader = Global.riyeder(kalimatSql);
if (Global.reader.HasRows)
    while (Global.reader.Read())
    {
        int idQuestion = Convert.ToInt32(Global.reader.GetValue(0)); 
        idQuestions.Add(idQuestion);
    }
Global.dbCon.Close();
foreach (int id in idQuestions)
    messageBox.Show(id.ToString());

I try to make edit it to function (class) so I can call it many times like this
private int sqlReader(string kalimatSql)
{
    int sqlReader(string kalimatSql){
    Global.dbCon.Open();
    List<int> idQuestions = new List<int>();
    Global.reader = Global.riyeder(kalimatSql);
    if (Global.reader.HasRows)
        while (Global.reader.Read())
        {
            int idQuestion = Convert.ToInt32(Global.reader.GetValue(0));
            idQuestions.Add(idQuestion);
        }
    Global.dbCon.Close();
    foreach (int id in idQuestions)
        return id;
}

but it's not working because not all code paths return a value... I wonder what's the correct way to do it?

A:

There are two issues with this last part of your code:
    foreach (int id in idQuestions) {
        return id;
    }
}

The primary issue here is that you're not returning anything if idQuestions is empty (which is why you're receiving this error). But even if it's not empty, your code is returning the first time you enter the foreach's body, thus returning only the first element from the list of ids. 
I'm assuming you want to return the entire list of ids, which is convenient because you already have them all inside of a List<>. Simply change your code to this:
    return idQuestions;
}

The complete method should look like this (note the method signature):
private List<int> sqlReader(string kalimatSql) {
    Global.dbCon.Open();
    List<int> idQuestions = new List<int>();
    Global.reader = Global.riyeder(kalimatSql);
    if (Global.reader.HasRows) {
        while (Global.reader.Read()) {
            int idQuestion = Convert.ToInt32(Global.reader.GetValue(0));
            idQuestions.Add(idQuestion);
        }
    }
    Global.dbCon.Close();

    //return the ids
    return idQuestions;
}

A:

this error occurred because, what will happened (or returned) when your last 'foreach' loop runs zero time?, in other sense what value should your code return when your 'idQuestions' has zero length?
in order to get rid of this, you change this code as
if(idQuestions.Count > 0)
{
    foreach (int id in idQuestions) {
       return id;
    }
}
else
    return -1;

