Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to fix Error CS0161; not all code path return a value c#?

I’m new to c# and I’m currently working on a program that reads the path of a textfile and then displays the longest word in that file. This is my code:

        static void Main(string[] args)
        {
            Console.WriteLine("Enter the path for a text file: ");
            var path = Console.ReadLine();
            Console.WriteLine(LongestWord(path));
        }

        public static string LongestWord(string path) 
        {
            var characters = new char[] { ' ', '.', ',', ';', '?', '\n', '\r' };
            var content = File.ReadAllText(path);
            var words = content.Split(characters);
            var list = new List<int>();
            if (File.Exists(path))
            {
                foreach (var word in words)
                {
                    list.Add(word.Length);
                }
                int max = list.Max();
                for (int i = 0; i < words.Length; i++)
                {
                    var count = words[i].ToCharArray();
                    if (count.Count() == max)
                    {
                        return words[i];
                    }
                }
            }
            else
            {
                return "You entered a file that could not be located";
            }

        }

As you see I tried making "Longestword" a method that I could use anywhere. This is when I get the named error. The code works otherwise if I use it in the same Main class.

I tried several "if" statements and exceptions but none of them seem to solve the problem.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The problem here is that there is a path of execution where no return statements are encountered. Specifically where the file is count, and opened, but then the if statement at the second for loop is never evaluated to true.

Now under normal execution, this should never happen, but this is technically possible. One way to resolve this is to throw an exception after this loop. But the best thing is to resolve the logic.

If you are comfortable using LINQ, the whole of:

            foreach (var word in words)
            {
                list.Add(word.Length);
            }
            int max = list.Max();
            for (int i = 0; i < words.Length; i++)
            {
                var count = words[i].ToCharArray();
                if (count.Count() == max)
                {
                    return words[i];
                }
            }

Can be replaced with:
return words.OrderByDescending(w => w.Length).First();

Otherwise a default value should be returned, something like null or the last element of the list.

Some other notes:
When using a string or an array, you can use the .Length property instead of the Linq Extension .Count(). .Length just retrieves the stored value (quickly), but .Count() would loop through the string/array every time (although Linq has optimizations to avoid this type of extra work)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading