[英]I am getting a 'not all code paths return a value' error in my c# code
I have written a c# extension method that returns any duplicate values in an array of ints and it is telling me that 'not all code paths return a value'.我编写了一个 c# 扩展方法,它返回整数数组中的任何重复值,它告诉我“并非所有代码路径都返回一个值”。 Here is my code:这是我的代码:
public static int? FindDuplicate(this int[] arrayToFindDuplicateIn)
{
int previousint = int.MaxValue;
arrayToFindDuplicateIn = arrayToFindDuplicateIn.OrderByDescending(x => x).ToArray();
foreach (int number in arrayToFindDuplicateIn)
{
if (number == previousint)
{
return number;
}
else
{
return null;
}
previousint = number;
}
}
If the array is empty, no value is returned, so just return something at the end or check the input array with arrayToFindDuplicateIn.Any()如果数组为空,则不返回任何值,因此只需在末尾返回一些内容或使用 arrayToFindDuplicateIn.Any() 检查输入数组
I think what you want is to remove your else return null;我想你想要的是删除你的 else return null; and put the return null;并把返回 null; outside your foreach.在你的 foreach 之外。 Otherwise it will only loop once everytime.否则每次只会循环一次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.