“not all code path return a value” error occurs in a method, but I did use some if statements to cover all scenario

谁说我不能喝 提交于 2020-04-30 04:33:26

问题


This may be a stupid question, but I just want to somebody can give a better explanation.

I have a method defined as below:

    private int Test(int i)
    {
        if (i < 0) return -1;
        if (i == 0) return 0;
        if (i > 0) return 1;

        //return 0;        
    }

It gives me this error "not all code path return a value".

I thought I had 3 if statement, which could cover all the scenarios(i<0, i==0, i>0). So it should not show me this error.


回答1:


The compiler just ain't that clever. Also, you're code is slightly inefficient in that it tests for a certainty (i must be greater than zero in the last case).

Write it as:

private int Test(int i)
{
    if (i < 0) return -1;
    else if (i == 0) return 0;
    else return 1;
}



回答2:


During compile-time, the compiler doesn't analyze the conditions and understands that they cover all the options - it just sees three unrelated if statements, and a path with no return if none of them are triggered.

You can make it "understand" by using else if and elses:

private int Test(int i)
{
    if (i < 0) return -1;
    else if (i == 0) return 0;
    else return 1;        
}



回答3:


If you want to keep your format, a way to do it is like this...

private int Test(int i)
{
   bool result = 1;

   if (i < 0) result = -1;
   if (i == 0) result = 0;
   if (i > 1) result = 1; //This is redundant because i is initialized to 1

   return result;
}


来源:https://stackoverflow.com/questions/61135896/not-all-code-path-return-a-value-error-occurs-in-a-method-but-i-did-use-some

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!