Ошибка 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 badges142 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 badges735 silver badges1002 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 badges105 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

3762 silver badges16 bronze badges

answered Feb 5, 2014 at 12:25

DareDevil's user avatar

DareDevilDareDevil

5,2396 gold badges50 silver badges88 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);

            }
        }
    }
}

Joker_23

1 / 1 / 0

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

Сообщений: 35

1

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

29.04.2022, 18:01. Показов 3597. Ответов 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

6403 / 3940 / 1578

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

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

29.04.2022, 18:46

3

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



0



Модератор

Эксперт С++

13320 / 10454 / 6253

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

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

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



1467 / 1008 / 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



1467 / 1008 / 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

6403 / 3940 / 1578

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

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

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

6403 / 3940 / 1578

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

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

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



1467 / 1008 / 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



1467 / 1008 / 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

1467 / 1008 / 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

6403 / 3940 / 1578

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

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

30.04.2022, 18:52

19

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

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

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

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

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

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

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



0



QuakerRUS

1467 / 1008 / 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



  • 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.

Возможно, вам также будет интересно:

  • Ошибка cs0120 для нестатического поля метода или свойства требуется ссылка на объект
  • Ошибка cs0115 form1 dispose bool не найден метод пригодный для переопределения
  • Ошибка cs0106 модификатор public недопустим для этого элемента
  • Ошибка cs0103 visual studio
  • Ошибка cs0021 не удается применить индексирование через к выражению типа int

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии