K
K
Kerim Rezai Shirazi2022-04-16 17:16:11
C++ / C#
Kerim Rezai Shirazi, 2022-04-16 17:16:11

What to do with error cs0161? Why can't I put return in curly braces?

Why can't I put return in curly braces? Writes not all paths return a value. And do not write about the visibility zone!

public static int[] GetFirstEvenNumbers(int count)
        {
          int [] array=new int[count];
            for (int i = 0; i < array.Length; i++)
            {
                int start = 2;
                array[i] = start + 2;
                return array;
            }
        }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
d-stream, 2022-04-17
@judge971

You can put return inside curly braces . But you also need to put other returns in all other places where the algorithm can "end".
A generalized-universal option is to put return at the very end before the last closing bracket. Plus, place additional ones where, logically, an "early answer" is obtained (in the question).

V
Vasily Bannikov, 2022-04-16
@vabka

C# actually swears that in some cases the loop may never be executed.
For example, if count =0
You just need to add one more return after the loop, or throw an exception

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question