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 [i].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.
If you remove the else if statement and add return false outside the for loop it should function correct.
C# is frequently wrong about this (well, really the compiler.) You can have [if(x==1) return true; if(x!=1) return false] and it isn't smart enough to know you've covered every case.
(But in this case, Suddoha is correct - it really is a problem with your code.)
Answer by Suddoha · Nov 08, 2016 at 10:29 PM
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 [i].ToLower ()))
{
return true;
}
}
return false;
}
Thanks for the explanation. I haven't needed to write a custom function with a returning value in a long time.