Error cs0161 not all code paths return a value

I've made a basic extension method to add retry functionality to my HttpClient.PostAsync: public static async Task PostWithRetryAsync(this HttpClient httpClient, Uri uri,

The simple reason is that the compiler has to be able to statically verify that all execution flow paths end up with a return statement (or an exception).

Let’s look at your code, it contains:

  • Some variables controlling a while loop
  • A while loop, with the return statement embedded
  • No return statement after the loop

So basically the compiler has to verify these things:

  1. That the while loop is actually executed
  2. That the return statement is always executed
  3. Or that some exception is always thrown instead.

The compiler is simply not able to verify this.

Let’s try a very simple example:

public int Test()
{
    int a = 1;
    while (a > 0)
        return 10;
}

This trivial example will generate the exact same error:

CS0161 ‘Test()’: not all code paths return a value

So the compiler is not able to deduce that because of these facts:

  • a is a local variable (meaning that only local code can impact it)
  • a has an initial value of 1, and is never changed
  • If the a variable is greater than zero (which it is), the return statement is reached

then the code will always return the value 10.

Now look at this example:

public int Test()
{
    const int a = 1;
    while (a > 0)
        return 10;
}

Only difference is that I made a a const. Now it compiles, but this is because the optimizer is now able to remove the whole loop, the final IL is just this:

Test:
IL_0000:  ldc.i4.s    0A 
IL_0002:  ret     

The whole while loop and local variable is gone, all is left is just this:

return 10;

So clearly the compiler does not look at variable values when it statically analyzes these things. The cost of implementing this feature and getting it right probably outweighs the effect or the downside of not doing it. Remember that «Every feature starts out in the hole by 100 points, which means that it has to have a significant net positive effect on the overall package for it to make it into the language.».

So yes, this is definitely a case where you know more about the code than the compiler.


Just for completeness, let’s look at all the ways your code can flow:

  1. It can exit early with an exception if maxAttempts is less than 1
  2. It will enter the while-loop since attempt is 1 and maxAttempts is at least 1.
  3. If the code inside the try statement throws a HttpRequestException then attempt is incremented and if still less than or equal to maxAttempts the while-loop will do another iteration. If it is now bigger than maxAttempts the exception will bubble up.
  4. If some other exception is thrown, it won’t get handled, and will bubble out of the method
  5. If no exception is thrown, the response is returned.

So basically, this code can be said to always end up either throwing an exception or return, but the compiler is not able to statically verify this.


Since you have embedded the escape hatch (attempt > maxAttempts) in two places, both as a criteria for the while-loop, and additionally inside the catch block I would simplify the code by just removing it from the while-loop:

while (true)
{
    ...
        if (attempt > maxAttempts)
            throw;
    ...
}

Since you’re guaranteed to run the while-loop at least once, and that it will actually be the catch block that exits it, just formalize that and the compiler will again be happy.

Now the flow control looks like this:

  • The while loop will always execute (or we have already thrown an exception)
  • The while loop will never terminate (no break inside, so no need for any code after the loop)
  • The only possible way to exit the loop is either an explicit return or an exception, neither of which the compiler has to verify any more because the focus of this particular error message is to flag that there is potentially a way to escape the method without an explicit return. Since there is no way to escape the method accidentally any more the rest of the checks can simply be skipped.

    Even this method will compile:

    public int Test()
    {
        while (true)
        {
        }
    }
    
  • 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.country == «US»)
                {
                    version = dataVersionsIdea.country + » » + dataVersionsIdea.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.

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

Position Is Everything: Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL.

Position is Everything

Joker_23

1 / 1 / 0

Регистрация: 22.04.2022

Сообщений: 35

1

Ошибка компиляции «не все по пути к коду возвращают значение»

29.04.2022, 18:01. Показов 2647. Ответов 21

Метки нет (Все метки)


Здравствуйте, помогите пожалуйста устранить ошибку CS0161 «Program.Main()»: не все по пути к коду возвращают значение

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
static long MathFib(int f)
{
    if (f < 1) return 0;
    if (f == 1) return 1;
    return MathFib(f - 1) + MathFib(f - 2);
}
 
namespace ConsoleApp1
{
    class Program
    {
 
        static void yuriy_1()
        {
            double y, x, k, chiss, summ, znamm;
            Console.WriteLine("x =");
            x = Convert.ToInt32(Console.ReadLine());
            k = 1;
            summ = 0;
            do
            {
                chiss = (1 / Math.Pow(k, 2));
                summ += chiss;
                k++;
            }
            while (Math.Abs(chiss) > Math.Pow(10, -5));
            znamm = Math.Pow(Math.Cos(Math.Pow(x, 2) - 3) / Math.Sin(Math.Pow(x, 2) - 3), 2);
            if (znamm != 0)
            {
                y = summ / znamm;
                Console.WriteLine($"y ={y}");
            }
            else
            {
                Console.WriteLine("Error");
            }
        }
        long yuriy_2()
        {
            int f;
            f = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("F = ");
            Console.WriteLine($"MathFib(f)");
            if (f <= 0)
            {
                Console.WriteLine("Errorn");
            }
            return 0;
        }
        int Main()
        {
            int x;
            Console.WriteLine("Vvedit chislo 1 abo 2 de 1 tse 1 zavdannya a 2 tse 2 zavdannyan");
            Console.WriteLine("Dlya vyhodu z programmi vvedit 999n");
            x = Convert.ToInt32(Console.ReadLine());
            switch (x)
            {
                case 1:
                    Console.WriteLine("zavdanya1n");
                    yuriy_1();
                    Main();
                    break;
                case 2:
                    Console.WriteLine("zavdanya2n");
                    yuriy_2();
                    Main();
                    break;
                case 999:
                    Environment.Exit(0);
                    break;
                default:
                    Main();
                    break;
            }
        }
    }
}

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Joker_23

1 / 1 / 0

Регистрация: 22.04.2022

Сообщений: 35

29.04.2022, 18:15

 [ТС]

2

Здравствуйте, помогите пожалуйста устранить ошибку CS0161 «Program.Main()»: не все по пути к коду возвращают значение

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
static long MathFib(int f)
{
    if (f < 1) return 0;
    if (f == 1) return 1;
    return MathFib(f - 1) + MathFib(f - 2);
}
 
namespace ConsoleApp1
{
    class Program
    {
 
        static void yuriy_1()
        {
            double y, x, k, chiss, summ, znamm;
            Console.WriteLine("x =");
            x = Convert.ToInt32(Console.ReadLine());
            k = 1;
            summ = 0;
            do
            {
                chiss = (1 / Math.Pow(k, 2));
                summ += chiss;
                k++;
            }
            while (Math.Abs(chiss) > Math.Pow(10, -5));
            znamm = Math.Pow(Math.Cos(Math.Pow(x, 2) - 3) / Math.Sin(Math.Pow(x, 2) - 3), 2);
            if (znamm != 0)
            {
                y = summ / znamm;
                Console.WriteLine($"y ={y}");
            }
            else
            {
                Console.WriteLine("Error");
            }
        }
        long yuriy_2()
        {
            int f;
            f = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("F = ");
            Console.WriteLine($"MathFib(f)");
            if (f <= 0)
            {
                Console.WriteLine("Errorn");
            }
            return 0;
        }
 
        private int Main()
        {
            int x;
            Console.WriteLine("Vvedit chislo 1 abo 2 de 1 tse 1 zavdannya a 2 tse 2 zavdannyan");
            Console.WriteLine("Dlya vyhodu z programmi vvedit 999n");
            x = Convert.ToInt32(Console.ReadLine());
            switch (x)
            {
                case 1:
                    Console.WriteLine("zavdanya1n");
                    yuriy_1();
                    Main();
                    break;
                case 2:
                    Console.WriteLine("zavdanya2n");
                    yuriy_2();
                    Main();
                    break;
                case 999:
                    Environment.Exit(0);
                    break;
                default:
                    Main();
                    break;
            }
        }
    }
}



0



Эксперт .NET

6269 / 3897 / 1567

Регистрация: 09.05.2015

Сообщений: 9,188

29.04.2022, 18:46

3

У вас у Main указан тип возвращаемого значения int и нет ни одного return…



0



Модератор

Эксперт С++

12641 / 10135 / 6102

Регистрация: 18.12.2011

Сообщений: 27,170

29.04.2022, 19:39

4

Цитата
Сообщение от Joker_23
Посмотреть сообщение

int Main()

И где возвращаете этот int?



0



13 / 8 / 5

Регистрация: 28.03.2022

Сообщений: 83

29.04.2022, 20:27

5

Цитата
Сообщение от zss
Посмотреть сообщение

И где возвращаете этот int?

а серьёзная ли это проблема? я просто курсач пишу, и у меня много где есть, где функция не возражает значение



0



1465 / 1006 / 456

Регистрация: 30.10.2017

Сообщений: 2,793

29.04.2022, 20:30

6

Цитата
Сообщение от maricruz
Посмотреть сообщение

а серьёзная ли это проблема?

Да нет. Просто программу не сможете скомпилировать и запустить. Является ли это проблемой, уже решайте сами.

Цитата
Сообщение от maricruz
Посмотреть сообщение

у меня много где есть, где функция не возражает значение

Не возвращают значения, если у них тип void.



0



13 / 8 / 5

Регистрация: 28.03.2022

Сообщений: 83

29.04.2022, 22:30

7

Цитата
Сообщение от QuakerRUS
Посмотреть сообщение

Просто программу не сможете скомпилировать и запустить

компилируется и запускается, визуал студиа 2022

Добавлено через 38 секунд

Цитата
Сообщение от QuakerRUS
Посмотреть сообщение

Не возвращают значения, если у них тип

я знаю, у меня в курсовой местами void и main



0



1465 / 1006 / 456

Регистрация: 30.10.2017

Сообщений: 2,793

30.04.2022, 00:52

8

Цитата
Сообщение от maricruz
Посмотреть сообщение

компилируется и запускается, визуал студиа 2022

Еще раз, оно не сможет скомпилироваться, если тип метода Main отличается от void или вы в конце метода не используете возврат значения через return.



0



13 / 8 / 5

Регистрация: 28.03.2022

Сообщений: 83

30.04.2022, 18:31

9

Цитата
Сообщение от QuakerRUS
Посмотреть сообщение

Еще раз, оно не сможет скомпилироваться, если тип метода Main отличается от void или вы в конце метода не используете возврат значения через return.

оно компилируется, НО пишется варнинг что не при всех условиях возращается значение



0



Эксперт .NET

6269 / 3897 / 1567

Регистрация: 09.05.2015

Сообщений: 9,188

30.04.2022, 18:33

10

Цитата
Сообщение от maricruz
Посмотреть сообщение

оно компилируется, НО пишется варнинг что не при всех условиях возращается значение

Оно НЕ компилируется. И там не варнинг, а ОШИБКА компиляции…

error CS0161: ‘Program.Main()’: not all code paths return a value



0



13 / 8 / 5

Регистрация: 28.03.2022

Сообщений: 83

30.04.2022, 18:34

11

Цитата
Сообщение от Someone007
Посмотреть сообщение

Оно НЕ компилируется. И там не варнинг, а ОШИБКА компиляции…

щас скрин дам



0



Эксперт .NET

6269 / 3897 / 1567

Регистрация: 09.05.2015

Сообщений: 9,188

30.04.2022, 18:35

12

Цитата
Сообщение от maricruz
Посмотреть сообщение

щас скрин дам

Зачем мне вас скрин, если и так всё известно. Вот даже пруф.



0



13 / 8 / 5

Регистрация: 28.03.2022

Сообщений: 83

30.04.2022, 18:39

13

Цитата
Сообщение от Someone007
Посмотреть сообщение

Оно НЕ компилируется. И там не варнинг, а ОШИБКА компиляции…

уже не дам, исправил всё, а, запускалось походу потому что у меня был return в функции main, у меня нехватало return’ов в других функциях типа int, у меня где-то в функции были выходы из нее,но не было return’a вконце функции, и писано что не при всех условиях возращается значение, вот наверно как

Добавлено через 1 минуту

Цитата
Сообщение от Someone007
Посмотреть сообщение

Зачем мне вас скрин, если и так всё известно. Вот даже пруф.

я ниже написал



0



1465 / 1006 / 456

Регистрация: 30.10.2017

Сообщений: 2,793

30.04.2022, 18:40

14

Цитата
Сообщение от maricruz
Посмотреть сообщение

не при всех условиях возращается значение

Не скомпилируется это, не важно, в Main или нет пропущен return.



0



13 / 8 / 5

Регистрация: 28.03.2022

Сообщений: 83

30.04.2022, 18:43

15

Цитата
Сообщение от QuakerRUS
Посмотреть сообщение

Не скомпилируется это, не важно, в Main или нет пропущен return.

да ёпрст, смотри, есть какая-то функция у меня, в ней есть где-то условие на выход(выход из функции у меня организован через return) и получается так что больше нигде у меня не прописан return( как я понимаю он ещё должен быть в конце ), код компилировался и было предупреждение что не при всех условиях возращается значение



0



1465 / 1006 / 456

Регистрация: 30.10.2017

Сообщений: 2,793

30.04.2022, 18:46

16

Цитата
Сообщение от maricruz
Посмотреть сообщение

код компилировался и было предупреждение что не при всех условиях

Это ошибка и код такой не скомпилируется. Можете попытаться привести код, который скомпилируется с таким якобы варнингом.



0



13 / 8 / 5

Регистрация: 28.03.2022

Сообщений: 83

30.04.2022, 18:47

17

Цитата
Сообщение от QuakerRUS
Посмотреть сообщение

варнингом

я уже все исправил в коде,это был не варнинг, а предупреждение

примерно писало вот так : Значение возвращается не при всех путях выполнения



0



QuakerRUS

1465 / 1006 / 456

Регистрация: 30.10.2017

Сообщений: 2,793

30.04.2022, 18:49

18

Цитата
Сообщение от maricruz
Посмотреть сообщение

я уже все исправил в коде

То есть вы не можете привести код. Хорошо, тогда я докажу обратное.

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
class Program
{
    static int Foo(int x)
    {
        if (x != 12345)
            return 1;
    }
 
    static void Main()
    {
        Foo(1);
    }
}

Код

error CS0161: "Program.Foo(int)": не все пути к коду возвращают значение.



0



Эксперт .NET

6269 / 3897 / 1567

Регистрация: 09.05.2015

Сообщений: 9,188

30.04.2022, 18:52

19

Цитата
Сообщение от maricruz
Посмотреть сообщение

код компилировался и было предупреждение что не при всех условиях возращается значение

Такого предупреждения в принципе не существует в C#…

Цитата
Сообщение от maricruz
Посмотреть сообщение

это был не варнинг, а предупреждение

Вы не поверите, но warning это и есть предупреждение…

Возможно вы попутали CS0161 и CS0162



0



QuakerRUS

1465 / 1006 / 456

Регистрация: 30.10.2017

Сообщений: 2,793

30.04.2022, 19:02

20

Цитата
Сообщение от Someone007
Посмотреть сообщение

Возможно вы попутали CS0161 и CS0162

Nice try. Тоже попробую вангануть.

Так как maricruz недавно создал тему в разделе C++, то делаю ставку на то, что он перепутал язык.

C++
1
2
3
4
5
6
7
8
9
10
int foo(int x)
{
    if (x != 12345)
        return 1;
}
 
int main()
{
    foo(1);
}

Код

warning C4715: foo: значение возвращается не при всех путях выполнения



0



Привет!

Я новичок в 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);

            }
        }
    }
}

Понравилась статья? Поделить с друзьями:
  • Error cs0149 method name expected
  • Error cs0139 no enclosing loop out of which to break or continue
  • Error cs0126 an object of a type convertible to int is required
  • Error cs0122 юнити
  • Error cs0122 unity