Search code examples
c#methodscompiler-errorsreturn-value

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'. 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;
        }
    }

Solution

  • I think what you want is to remove your else return null; and put the return null; outside your foreach. Otherwise it will only loop once everytime.