Not all code paths return a value error. Fixing the error breaks my function. Ideas?

Not sure how to solve this issue. If I use this code that I made:

public bool ContainsCursing(string name) {

		for (int i = 0; i < ScreenedWords.Length; i++) {
			if (name.ToLower ().Contains (ScreenedWords *.ToLower ())) {*
  •  		return true;*
    
  •  	} else if (i >= ScreenedWords.Length) {*
    
  •  		return false;*
    
  •  	}* 
    
  •  }*
    
  • }*
    I get the error: “Not all code paths return a value”. I can fix the error by adding “return true” outside of the for loop. But then, instead of being a syntax error, it’s a logic error (if you get what I mean). Now my function will always return true no matter what. So how can I fix this? I tried “return null”, that gives me the error “Cannot convert null to `bool’ because it is a value type”. The function only has 2 possible code paths, and both of them return a value so I’m not sure why Unity can’t recognize that. Any ideas, people? Thanks.

The function does not only have 2 possible paths.
The for loop might not even run once if the ScreenedWords.Length is 0. So that’s a case which is not being covered here.

Even if it executes, the ‘else if’ kills it all, because ‘else if’ is not ‘else’. There’s still a condition to be met (even if yours will never be met in a single-threaded (or correctly multi-threaded, i.e. thread-safe) environment).

And that’s because you’ve got a logical error in your existing code.

Assuming that there’s no other thread which could (theoretically) remove items during the iteration, the ‘else if’ part will never be reached as you only ever iterate as long as ’ i < ScreenedWords.Length ’ which excludes ’ i >= ScreenedWords.Length '.

This being said, just let that case alone, it’s covered by the case that no match has been found (which also includes that the for loop doesn’t even run once) and that can be written as:

public bool ContainsCursing(string name) 
{
    for (int i = 0; i < ScreenedWords.Length; i++) 
    {
        if (name.ToLower ().Contains (ScreenedWords *.ToLower ()))* 

{
return true;
}
}
return false;
}