Ошибка cs0161 не все пути к коду возвращают значение

Не все пути к коду возвращают значение — значит, что есть такие параметры, при которых функция, которая должна вернуть значение, выполнит команду return — то есть не вернет значение. Это может произойти по разным случаям: вы не написали команду return, вы написали ее в условии, которое не всегда истинно, ИЛИ вы написали ее в цикле, который может не дойти до этой строки.

Проще говоря, представьте, что произойдет, если на вход в функцию попадет неположительное число.

Если вы хотите посчитать сумму чисел от 1 до N, то возвращение результата должно будет после цикла, когда результат переменной result сформировался окончательно:

static int Sum(int number)
        {
            int result = 0;
            for (int i = 1; i <= number; i++)
            {
                result += i;
            }
            return result;
        }

I’m trying to write code that returns whether or not a given integer is divisible evenly by 1 to 20,
but I keep receiving the following error:

error CS0161: ‘ProblemFive.isTwenty(int)’: not all code paths return a value

Here is my code:

public static bool isTwenty(int num)
{
    for(int j = 1; j <= 20; j++)
    {
        if(num % j != 0)
        {
            return false;
        }
        else if(num % j == 0 && num == 20)
        {
            return true;
        }
    }
}

user2864740's user avatar

user2864740

59.6k15 gold badges141 silver badges215 bronze badges

asked Jan 17, 2014 at 20:47

user115185's user avatar

2

You’re missing a return statement.

When the compiler looks at your code, it’s sees a third path (the else you didn’t code for) that could occur but doesn’t return a value. Hence not all code paths return a value.

For my suggested fix, I put a return after your loop ends. The other obvious spot — adding an else that had a return value to the if-else-if — would break the for loop.

public static bool isTwenty(int num)
{
    for(int j = 1; j <= 20; j++)
    {
        if(num % j != 0)
        {
            return false;
        }
        else if(num % j == 0 && num == 20)
        {
            return true;
        }
    }
    return false;  //This is your missing statement
}

answered Jan 17, 2014 at 20:53

4

The compiler doesn’t get the intricate logic where you return in the last iteration of the loop, so it thinks that you could exit out of the loop and end up not returning anything at all.

Instead of returning in the last iteration, just return true after the loop:

public static bool isTwenty(int num) {
  for(int j = 1; j <= 20; j++) {
    if(num % j != 0) {
      return false;
    }
  }
  return true;
}

Side note, there is a logical error in the original code. You are checking if num == 20 in the last condition, but you should have checked if j == 20. Also checking if num % j == 0 was superflous, as that is always true when you get there.

answered Jan 17, 2014 at 21:48

Guffa's user avatar

GuffaGuffa

685k108 gold badges733 silver badges1000 bronze badges

0

I also experienced this problem and found the easy solution to be

public string ReturnValues()
{
    string _var = ""; // Setting an innitial value

    if (.....)  // Looking at conditions
    {
        _var = "true"; // Re-assign the value of _var
    }

    return _var; // Return the value of var
}

This also works with other return types and gives the least amount of problems

The initial value I chose was a fall-back value and I was able to re-assign the value as many times as required.

Alan Moore's user avatar

Alan Moore

6,5256 gold badges54 silver badges68 bronze badges

answered Jul 27, 2014 at 14:25

Evert's user avatar

EvertEvert

811 silver badge2 bronze badges

I like to beat dead horses, but I just wanted to make an additional point:

First of all, the problem is that not all conditions of your control structure have been addressed. Essentially, you’re saying if a, then this, else if b, then this. End. But what if neither? There’s no way to exit (i.e. not every ‘path’ returns a value).

My additional point is that this is an example of why you should aim for a single exit if possible. In this example you would do something like this:

bool result = false;
if(conditionA)
{
   DoThings();
   result = true;
}
else if(conditionB)
{
   result = false;
}
else if(conditionC)
{
   DoThings();
   result = true;
}

return result;

So here, you will always have a return statement and the method always exits in one place. A couple things to consider though… you need to make sure that your exit value is valid on every path or at least acceptable. For example, this decision structure only accounts for three possibilities but the single exit can also act as your final else statement. Or does it? You need to make sure that the final return value is valid on all paths. This is a much better way to approach it versus having 50 million exit points.

answered Jan 27, 2014 at 6:29

Sinaesthetic's user avatar

SinaestheticSinaesthetic

11.3k27 gold badges104 silver badges175 bronze badges

Or simply do this stuff:

public static bool isTwenty(int num)
{
   for(int j = 1; j <= 20; j++)
   {
      if(num % j != 0)
      {
          return false;
      }
      else if(num % j == 0 && num == 20)
      {
          return true;
      }
      else
      {
          return false; 
      }
   }
}

ForceVII's user avatar

ForceVII

3772 silver badges16 bronze badges

answered Feb 5, 2014 at 12:25

DareDevil's user avatar

DareDevilDareDevil

5,2396 gold badges50 silver badges87 bronze badges

1

Have a look at this one. It is the Ternary operator in C#.

bool BooleanValue = (num % 3 != 0) ? true : false;

This is just to show the principle; you can return True or False (or even integer or string) depending on the outcome of something on the left side of the question mark. Nice operator, this.

Three alternatives together:

      public bool test1()
        {
            int num = 21;
            bool BooleanValue = (num % 3 != 0) ? true : false;
            return BooleanValue;
        }

        public bool test2()
        {
            int num = 20;
            bool test = (num % 3 != 0);
            return test;
        }

Even Shorter:

public bool test3()
{
    int num = 20;
    return (bool)(num % 3 != 0);
}

answered Jan 18, 2014 at 22:50

netfed's user avatar

netfednetfed

6028 silver badges18 bronze badges

class Program
{
    double[] a = new double[] { 1, 3, 4, 8, 21, 38 };
    double[] b = new double[] { 1, 7, 19, 3, 2, 24 };
    double[] result;


    public double[] CheckSorting()
    {
        for(int i = 1; i < a.Length; i++)
        {
            if (a[i] < a[i - 1])
                result = b;
            else
                result = a;
        }
        return result;
    }

    static void Main(string[] args)
    {
        Program checkSorting = new Program();
        checkSorting.CheckSorting();
        Console.ReadLine();
    }
}

This should work, otherwise i got the error that not all codepaths return a value. Therefor i set the result as the returned value, which is set as either B or A depending on which is true

answered Jun 1, 2017 at 13:16

Douglas Pettersson's user avatar

This usually happens to me if I misplace a return statement, for example:
enter image description here

Adding a return statement, or in my case, moving it to correct scope will do the trick:
enter image description here

answered Dec 6, 2019 at 15:57

Mirza Sisic's user avatar

Mirza SisicMirza Sisic

2,3914 gold badges24 silver badges37 bronze badges

1

Not all code paths return a value.

Solution: To solve the error, make sure to return a value from all code paths in the function or set noImplicitReturns to false in your tsconfig.json file.

setzamora's user avatar

setzamora

3,5306 gold badges34 silver badges48 bronze badges

answered Jan 28 at 17:09

Jeeva M's user avatar

Привет!

Я новичок в C# и недавно начал изучать функции. Мне надо сделать программу которая запрашивает числа, знак и выполняет действие (калькулятор короче). Но я столкнулся с проблемой, вот как она звучит:
Серьезность Код Описание Проект Файл Строка Состояние подавления
Ошибка CS0161 ‘»Program.Nikita(int, int, char)»: не все пути к коду возвращают значение.
вот код программы:

public static int Nikita(int a, int b, char d)
        {
            switch (d)

            {
                case '+':
                  return a + b;
                case '-':
                  return a - b;
                case '*':
                  return a * b;
                case '/':
                  return a / b;
                default:
                   Console.WriteLine("Ошибка");
                   break;


            }
            //return a - b;
        }
        static void Main(string[] args)
        {   
            {
                Console.Write("вевдите первое число: ");
                int am = (int)Convert.ToInt64(Console.ReadLine());
                Console.Write("введите знак: ");
                char dm = Convert.ToChar(Console.ReadLine());
                Console.Write("введите второе число: ");
                int bm = (int)Convert.ToInt64(Console.ReadLine());
                int resault = Nikita(am, bm, dm);
                Console.WriteLine(am);
                Console.WriteLine(bm);
                Console.WriteLine(dm);
                Console.WriteLine(resault);

            }
        }
    }
}

How to fix not all code paths return a valueWhen you run a set of instructions on your program and it displays not all code paths return a value, it’s an error message. It is caused because the compiler has hit the end of the function without the return statement. The return statement ends the execution of the function and returns a value to the calling function.

If you want to know why you keep receiving the error message, our coding experts are here to help you out!

Contents

  • Why Is Your System Displaying Not All Code Paths Return a Value?
    • – What Happens if There Is No Return Statement in Your Code?
  • How To Solve This Error
    • – Example 1: Fixing the Error While Using C# Program
    • – Example 2: Not All Code Paths Return a Value For C#
    • – Example 3: Fixing the Error While in JavaScript
    • – Example 4: Fixing the Error While Using Typescript
    • – Example 5: Not All Code Paths Return a Value in Lambda Expression
  • FAQs
    • – Which One Is Better, Using”If-else” or “Return”?
    • – What Is the Use of Return Value in Java?
  • Conclusion

Why Is Your System Displaying Not All Code Paths Return a Value?

Your system is displaying that not all code paths return a value error because there should be at least one route that returns a value to the caller but, in this case, there is no route through your function that returns a value. The error message means that the compiler found a way to hit the end of the function without a return statement that tells it what it’s supposed to return.

Another cause of the warning message appearing can be caused if there is no return statement in your code.

– What Happens if There Is No Return Statement in Your Code?

If no return statement appears in a function definition, control automatically returns to the calling function after the last statement of the called function is executed. In this case, the return value of the called function is undefined. If the function has a return type other than void, it’s a serious bug, and the compiler displays an error message.

We recommend that you always use a plain return statement to make your intent clear.

How To Solve This Error

The warning message is common for almost all programming languages such as Lambda, JavaScript, jQuery, C#, PHP, PowerShell 5, and so on.

So, to fully cover the error, we will consider some examples of this error for a couple of programming languages.

– Example 1: Fixing the Error While Using C# Program

Here is an example of a code path that does not return a value resulting in an error when using c# to program:

public bool FindItem(GameObject item)
{
for (int i = 0; i < MyInventory.Length; i++)
{
if (MyInventory[i] == item)
{
//we found the item
return true;
}
//if item not found
return false;
}
}

Result:

Assets/Script/Items/InventoryScript.cs(35,17):error CS0161: `InventoryScript.FindItem(UnityEngine.GameObject)’: not all code paths return a value eslint

Solution:

public bool FindItem(GameObject item) {
return System.Array.IndexOf(MyInventory, item) >= 0;
}

Result:

Assets/Script/Items/InventoryScript.cs(35,17): error CS0161: `InventoryScript.FindItem(UnityEngine.GameObject)’: not all code paths return a value

Problem: The error here is that for loop, we set I = 0. In this case, the test failed because I < My inventory. length which isn’t valid as zero is not less than zero. Since the test failed, the function exits the for loop immediately without checking the following code and not returning true or false. And here we see the error message because we haven’t encountered a return statement.

To fix this problem, we will need to move the return false statement outside the loop to the very end of the function. The loop will check whether the item is in MyInventory [0], and if not, it will always return false before it gets a chance to check MyInventory [1]. We will want to return true if and only if the program ran through the whole array and didn’t find the item, not immediately after a single mismatch.

We recommend you use this solution:

Solution:

public bool FindItem(GameObject item) {
return System.Array.IndexOf(MyInventory, item) >= 0;
}

– Example 2: Not All Code Paths Return a Value For C#

Here is another example if you receive this error message when using c# to program.

We will run a program on the bool value function to see the error.

class Program
{
static void Main(string[] args)
{
bool myChoice = true;
while (myChoice)
{
myChoice = ChoiceGame();
}
}
private static bool ChoiceGame()
{
char Choice;
string Con = “y”;
Console.WriteLine(“What is the command keyword to exit a loop in C#?”);
Console.WriteLine(“a. Quit”);
Console.WriteLine(“b. Continue”);
Console.WriteLine(“c. break”);
Console.WriteLine(“d. exit”);
while (Con == “y”)
{
Console.WriteLine(“Enter Your Choice:”);
Choice = (char)Console.Read();
if (Choice == ‘c’)
{
Console.WriteLine(“Congratulations”);
return false;
}
else if (Choice == ‘a’ || Choice == ‘b’ || Choice == ‘d’)
{
Console.WriteLine(“Incorrect”);
Console.WriteLine(“Again?press y to continue”);
Con = Console.ReadLine().ToString();
return true; }
else
{
Console.WriteLine(“Invalid choice”);
return false;
}
}
}. (solution here)
}

Result: not all code paths return a value c#

Solution: Here in the function, we are returning value for if and else if and then for else. In the if-else statement we selected “c”, “a”, “b”, “d”. There is a logical error here – the compiler doesn’t understand that we will always be in a while loop, and this is why it is showing an error.

After the else returns false, the function should return the while loop false.

– Example 3: Fixing the Error While in JavaScript

If you receive the error message while using JavaScript, it means that in your program there is an instance where your return statement is not returning a value to the calling function.

Let’s consider an example where the set of instructions leads to an error and the possible solution.

document.getElementById(‘search_field’).onkeypress = function(e) {
if (!e) e = window.event;
var keyCode = e.keyCode || e.which;
if (keyCode == ’13’) {
window.location.href = ‘/search/?s=’ + $(‘#search_field’).val();
return false;
}
};

We know that the last bracket will show you an error if you try it, indicating that there is a problem with the code.

To solve the error, try returning the if statement true.

Possible solution:

document.getElementById(‘search_field’).onkeypress = function(e) {
if (!e) {
e = window.event;
}
var keyCode = e.keyCode || e.which;
if (keyCode == ’13’) {
window.location.href = ‘/search/?s=’ + $(‘#search_field’).val();
return false;
}
return true;
};

– Example 4: Fixing the Error While Using Typescript

Let’s consider another example – a Typescript code path that does not return a value, resulting in an error.

public MakeMove(board: Board): boolean {
var pos = this.clickedPosition;
this.clickedPosition = null;
if (null === pos) {
return false;
}
if (this.id === pos.player) {
if (board.GetStones(pos) > 0) {
var finalDrop = board.Sow(pos);
board.Capture(pos.player, finalDrop);
} else {
alert(“Select a house with at least 1 stone!”);
}
} else {
alert(“Select a house from your side!”);
}
}

The mystery here is that, if you remove all the return statements, you will get the expected error.

Result: not all code paths return a value.ts(7030) typescript

– Example 5: Not All Code Paths Return a Value in Lambda Expression

Here is an example of a code path that does not return a value resulting in an error when using Lambda. It means your return statement is not working.

Let’s call a function CountPixels

Task<int> task1 = newTask<int> (() => {CountPixels (croppedBitmap, colour angle.fromArgb (255, 255, 255, 255));});

In the end, we will get an error because we didn’t return CountPixels.

Also, when using PowerShell 5, you can receive an error message, not all code paths return value within method powershell. Now you know what this means.

FAQs

– Which One Is Better, Using”If-else” or “Return”?

They are equally efficient, but the return is usually considered to give better readability, especially when used to eliminate several nested conditions.

Note:

The return should be the last line in the function which returns either a specified value or the last variable assignment in the function. The if-else is meant to conditionally execute code if your test premise is false.

if /* some condition is not met */
return
if /* another requirement is not met */
return
if /* yet another requirement fails */
return
/* now we know it’s OK to proceed */
/*
the “real” work of the procedure begins here
*/

– What Is the Use of Return Value in Java?

The return is used in Javascript, not as an identifier but to exit from a method with or without a value.

Let’s consider an example you can try by yourself. A method with a return value:

public class Main {
static int myMethod(int x) {
return 5 + x;
}
public static void main(String[] args) {
System.out.println(myMethod(3));
}
}
// Outputs 8 (5 + 3)

Conclusion

Now that you have read our article, you won’t find it difficult to solve code path errors again in your function because our coding experts have shown you possible problems and their solutions. Let’s see some of the points we mentioned in the article:

  • The error message is caused whenever the return statement is unable to return a value to the calling function
  • The set of instructions in our programming is known as code path
  • The return statement simply means an exit point from a function
  • The error message can be seen in programming languages such as JavaScript, jQuery, PHP, Dartz, and so on.
  • A function continues to run infinitely unless it is returned

Not all code paths return a valueThe function of the return statement cannot be underrated as it gives the code better readability.

  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

  • Remove From My Forums
  • Question

  • I am getting the following error I understand I am missing something but I have no idea what as I am still learning. Any help would be great

    error message:

    —— Build started: Project: e:projectsChromeWebService, Configuration: Debug .NET ——
    Validating Web Site
    Building directory ‘/ChromeWebService/App_WebReferences/’.
    Building directory ‘/ChromeWebService/App_Code/’.

    e:projectsChromeWebServiceApp_CodeChromeWebService.cs(27,19): error CS0161: ‘ChromeWebService.getVin()’: not all code paths return a value
    Validation Complete
    ========== Build: 0 succeeded or up-to-date, 1 failed, 0 skipped ==========

    Here is the code:

    using System;
    using System.Web;
    using System.Collections;
    using System.Web.Services;
    using System.Web.Services.Protocols;
    using com.chrome.platform.AutomotiveDescriptionService5;

    /// <summary>
    /// Summary description for ChromeWebService
    /// </summary>
    [WebService(Namespace = «http://arknet.arkona.com/ChromeWebService»)]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class ChromeWebService : System.Web.Services.WebService {

        public ChromeWebService () {

            //Uncomment the following line if using designed components
            //InitializeComponent();

        }

        [WebMethod]
        public string getVin()
        {

            AutomotiveDescriptionService5 ads = new AutomotiveDescriptionService5();

            AccountInfo accountInfo = new AccountInfo();
            accountInfo.accountNumber = «xxxxxxxx»;
            accountInfo.accountSecret = «xxxxxxxxxxxx»;
            accountInfo.locale = new Locale();
            accountInfo.locale.language = «en»;
            accountInfo.locale.country = «US»;
            String Vin = «»;
            String manufactureModelCode = «»;
            String trimName = «»;
            String manufactoureOptionCodes = «»;
            String equipmentDescriptions = «»;
            String wheelBase = «»;
            String exteriorColorName = «»;
            String useSafeStandards = «»;
            String excludeFleetOnlyStyles = «»;
            String includeAvailableEquipment = «»;
           

            String version = «»;
            DataVersionsRequest dataVersionRequest = new DataVersionsRequest();
            dataVersionRequest.accountInfo = accountInfo;
            DataVersion[] dataVersions = ads.getDataVersions(dataVersionRequest);
            for (int i = 0; i < dataVersions.Length; i++)
            {
                if (dataVersionsIdea

    Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

    Position is Everything

  • Remove From My Forums
  • Question

  • I am getting the following error I understand I am missing something but I have no idea what as I am still learning. Any help would be great

    error message:

    —— Build started: Project: e:projectsChromeWebService, Configuration: Debug .NET ——
    Validating Web Site
    Building directory ‘/ChromeWebService/App_WebReferences/’.
    Building directory ‘/ChromeWebService/App_Code/’.

    e:projectsChromeWebServiceApp_CodeChromeWebService.cs(27,19): error CS0161: ‘ChromeWebService.getVin()’: not all code paths return a value
    Validation Complete
    ========== Build: 0 succeeded or up-to-date, 1 failed, 0 skipped ==========

    Here is the code:

    using System;
    using System.Web;
    using System.Collections;
    using System.Web.Services;
    using System.Web.Services.Protocols;
    using com.chrome.platform.AutomotiveDescriptionService5;

    /// <summary>
    /// Summary description for ChromeWebService
    /// </summary>
    [WebService(Namespace = «http://arknet.arkona.com/ChromeWebService»)]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class ChromeWebService : System.Web.Services.WebService {

        public ChromeWebService () {

            //Uncomment the following line if using designed components
            //InitializeComponent();

        }

        [WebMethod]
        public string getVin()
        {

            AutomotiveDescriptionService5 ads = new AutomotiveDescriptionService5();

            AccountInfo accountInfo = new AccountInfo();
            accountInfo.accountNumber = «xxxxxxxx»;
            accountInfo.accountSecret = «xxxxxxxxxxxx»;
            accountInfo.locale = new Locale();
            accountInfo.locale.language = «en»;
            accountInfo.locale.country = «US»;
            String Vin = «»;
            String manufactureModelCode = «»;
            String trimName = «»;
            String manufactoureOptionCodes = «»;
            String equipmentDescriptions = «»;
            String wheelBase = «»;
            String exteriorColorName = «»;
            String useSafeStandards = «»;
            String excludeFleetOnlyStyles = «»;
            String includeAvailableEquipment = «»;
           

            String version = «»;
            DataVersionsRequest dataVersionRequest = new DataVersionsRequest();
            dataVersionRequest.accountInfo = accountInfo;
            DataVersion[] dataVersions = ads.getDataVersions(dataVersionRequest);
            for (int i = 0; i < dataVersions.Length; i++)
            {
                if (dataVersions.country == «US»)
                {
                    version = dataVersionsIdea.country + » » + dataVersionsIdea.country + » » + dataVersions.build + » (» +
                        dataVersionsIdea.date + «)»;
                }
            }

            VehicleInformation vehicleInfo = null;
            if (Vin != null && Vin.Length > 0)
            {
                VehicleInformationFromVinRequest vinRequest = new
                    VehicleInformationFromVinRequest();
                vinRequest.accountInfo = accountInfo;

                vinRequest.vin = Vin;
                vinRequest.manufacturerModelCode = manufactureModelCode;
                vinRequest.trimName = trimName;
                if (manufactoureOptionCodes.Length > 0)
                {
                    vinRequest.manufacturerOptionCodes = manufactoureOptionCodes.Split(new char[] { ‘,’ });
                }
                if (equipmentDescriptions.Length > 0)
                {
                    vinRequest.equipmentDescriptions = equipmentDescriptions.Split(new char[] { ‘,’ });
                }
                if (wheelBase.Length > 0)
                {
                    vinRequest.wheelBase = Double.Parse(wheelBase);
                }
                vinRequest.exteriorColorName = exteriorColorName;
                vinRequest.useSafeStandards = useSafeStandards != null;
                vinRequest.excludeFleetOnlyStyles = excludeFleetOnlyStyles != null;
                vinRequest.includeAvailableEquipment = includeAvailableEquipment != null;

                vinRequest.enableEnrichedVehicleEquipment = false;

                vehicleInfo = ads.getVehicleInformationFromVin(vinRequest);

    }

    Thank you for taking the time to look at this.

Answers

  • got the answer I needed public void getVin() instead of public string getVin() whelp still learning

  • The message is telling you that the problem lies in a method called ‘ChromeWebService.getVin’.  The problem is that there are some code paths (i.e., some routes through the code in getVin) that cause getVin to exit without returning a value. 

    Since getVin is declared to be of type string, all paths through the method should end up calling return.

    For example, in the code below, the execution path through the method «foo» returns the value «a string» if expression evaluates to true.  But, if expression evaluates to false then the code path just drops down to the end of «foo» and exits the method without calling return which would cause a CS0161 error.

    Uncommenting either of the commented return statements would fix the error.

    Code Snippet

    string foo()

    {

       bool expression = true;

       if (expression)

       {

          return «a string»;

       }

       else

       {

          // should return something here…

          //return «another string»;

       }

       // … or return something here

       //return «yet another string»;

    }

    All the compiler error messages are should be documented in the MSDN library.  Go to msdn.microsoft.com and enter CS0161 in the search box and you should get an explaination of the error and some sample code demonstrating how the error can be caused.

Понравилась статья? Поделить с друзьями:
  • Ошибка cs0106 модификатор public недопустим для этого элемента
  • Ошибка cs0106 модификатор private недопустим для этого элемента
  • Ошибка cs0103 имя initializecomponent не существует в текущем контексте
  • Ошибка cs0101 пространство имен уже содержит определение для
  • Ошибка cs0004 pubg на ps4