Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# not all code paths return a value error in simple method

Tags:

c#

Simple program for class to count words and getting the error above and it driving me mad.

int words; //variable to hold word count.

//WordCount methos will count the spaces and punciation.
private int WordCount(string str)
{
    int words = 0; //the number of words counted

    //count the white spaces and punctuation.
    foreach (char ch in str)
    {
        if (char.IsWhiteSpace(ch))
        {
            words++;
        }
        if (char.IsPunctuation(ch))
        {
            words++;
        }

        //return number of words
        return words;
    }
}
like image 390
Mosep Avatar asked Mar 19 '26 17:03

Mosep


2 Answers

If the string will be empty the return command will not be executed..

Use this instead:

//WordCount methos will count the spaces and punciation.
private int WordCount(string str)
{
    int words = 0; //the number of words counted

    //count the white spaces and punctuation.
    foreach (char ch in str)
    {
        if (char.IsWhiteSpace(ch))
        {
            words++;
        }
        if (char.IsPunctuation(ch))
        {
            words++;
        }
   }

   //return number of words
   return words;
}
like image 122
Tomzan Avatar answered Mar 22 '26 05:03

Tomzan


Your code is returning from inside of foreach loop, if the parameter passed is null, you will get an exception, if it is an empty string, execution will not enter the loop hence the error.

Your current method is also incorrect logically since it will return after first iteration, possibly giving you incorrect result. Your return statement should be outside of foreach loop

like image 35
Habib Avatar answered Mar 22 '26 07:03

Habib



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!