Search code examples
c#if-statementforeachreturn-valuenested-loops

Why Am I getting "Not All paths return a value" when using if inside a foreach


I'm trying to return a value once it finds the string match. I'm using the following code.

MetadataIcons mi = new MetadataIcons();
Type me = mi.GetType();
PropertyInfo[] pi = me.GetProperties();

foreach (var property in pi)
    if (property.Name.ToLower().Equals(prop.ToLower()))
        return property.GetValue(prop).ToString();

But, I get the error "Not all paths return a value" I thought I was able to do so that way. Do I really need to specific a return variable?


Solution

  • When you declare a function to have a return value in c#, you must return something of the same datatype or throw an exception. Your code lacks an "else" situation, so you're not returning anything. If you want a default value, explicitly place it in your "else". Otherwise, you may want to declare an ApplicationException and throw it (which counts as a return value in a way).

    In your specific situation, it's better to declare a variable first, then use the loop to assign its value, then return that. This skips the need for an else if you initialize it.

     string retval = string.Empty;
        foreach (var property in pi)
            if (property.Name.ToLower().Equals(prop.ToLower()))
                {
                   retval = property.GetValue(prop).ToString();
                   break; //stop looping
                }
    
        return retval;
    

    You can also use ! to negate the if boolean result and do it this way:

        string retval = string.Empty;
            foreach (var property in pi)
            {
                if (!(property.Name.ToLower().Equals(prop.ToLower())))
                    {
                       continue; //jump out of this iteration and go to the next                  
                    }
                retval = property.GetValue(prop).ToString();              
            }
            return retval;