简体   繁体   中英

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.

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)

You have no return statement after if (count.Count() == max) . You shall also check if file is not empty. If file doesn't exists it's better to throw an exception. You are trying to read file before checking if it exists, if the file doesn't exists you will get exception.

static string? LongestWord(string path) {
    var characters = new char[] { ' ', '.', ',', ';', '?', '\n', '\r' };
    var list = new List<int>();
    string result = string.Empty;
    if (File.Exists(path)) {
        var content = File.ReadAllText(path);
        if(content.Length > 0) {
            var words = content.Split(characters);
            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) {
                    result = words[i];
                }
            }
            return result;
        } else {
            return null; //Or throw exception
        }
    } else {
        throw new FileNotFoundException();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM