开发者

What causes the error "Not all code paths return a value"?

public string Valid(OleDbDataReader myreader, int stval)
{
    object val = myreader[stval];

    if (val != DBNull.Value)
    {
        return val.ToString() ;
    }
    else
    {
        Convert.开发者_如何学PythonToString(0);
    }
}

There is a Error " not all code paths return a value" please Help


You need to read about basic of C functions.

As function returning string value it must return a value in all cases. This includes the else part also.

The reason is if there else part is executed than you need to return string value, but there is no return there:

public string Valid(OleDbDataReader myreader, int stval)
    {
        object val = myreader[stval];
        if (val != DBNull.Value)
        {
            return val.ToString() ;
        }
        else
        {
           return Convert.ToString(0); //forgot to write return over her
        }
    }


When you create a function that is meant to return a value, you need to ensure that all possible paths through that function eventually return a value.

In your case, no value is returned if myreader[stval] is equal to DBNull.Value since it will enter the else clause and simply drop through to the end of the function, returning nothing:

public string Valid(OleDbDataReader myreader, int stval)
{
    object val = myreader[stval];
    if (val != DBNull.Value)
    {
        return val.ToString() ;
    }
    else
    {
        Convert.ToString(0);
    }
}

My own personal opinion is that this would be better written as:

public string Valid (OleDbDataReader myreader, int stval) {
    object val = myreader[stval];

    if (val != DBNull.Value)
        return val.ToString() ;

    return Convert.ToString(0);
}

In other words, it's often better to provide a default case at the end to ensure this can't happen. I cringe whenever I see code of the form:

if something:
    return or exit
else:
    do something else

since it's needlessly complex and can lead to exactly the sort of problem described here in your question (as well as indentation hell). Far better (again, this is my opinion but it's backed by way too many years of experience) to use the simpler:

if something:
    return or exit
do something else
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜