C
C#3y ago
yatta

How to write function in .net6? [Answered]

I try .net6 for the first time and i got an error ask me to provide return value regardless that i already provided one.
8 Replies
MechWarrior99
MechWarrior993y ago
That only returns if the condition in the if statement is true. You need a return regardless of conditions.
yatta
yattaOP3y ago
like this ? but error still there
MechWarrior99
MechWarrior993y ago
No, because now the for loop will only run ones.
static int Search(int[] nums, int target)
{
for(int i = 0; i < nums.Length; i++)
{
if (nums[i] == target)
return i;
}

return -1;
}
static int Search(int[] nums, int target)
{
for(int i = 0; i < nums.Length; i++)
{
if (nums[i] == target)
return i;
}

return -1;
}
Tvde1
Tvde13y ago
there is no guarantee that the code will enter the for loop
MechWarrior99
MechWarrior993y ago
You need to add a return at the very end where it is not based on any conditions or anything. Sort of like fallback if everything else fails/doesn't run at least that will return.
yatta
yattaOP3y ago
sound like something in C
Tvde1
Tvde13y ago
also, .IndexOf exists :)
[1, 5, 7, 3, 12, 54].IndexOf(7); => 2
[1, 5, 7, 3, 12, 54].IndexOf(7); => 2
Accord
Accord3y ago
✅ This post has been marked as answered!

Did you find this page helpful?