S
S
Sergey Zolotarev2020-09-16 14:47:38
Algorithms
Sergey Zolotarev, 2020-09-16 14:47:38

How to correctly define the return path to the function value code?

Good afternoon!
At the beginning of the question, I provide the code for the function for determining the existence of a specialty, written in C#:

public static bool isProf(string special)
        {
            dynamic sl = JObject.Parse(File.ReadAllText(@"..\..\..\..\data\source\specialization.json"));

            foreach (var property in sl.specialization)
            {
                if (property == special)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

Function type : Boolean
Function parameter type : String When

entering a specialty in the data accounting program, the user sends the entered specialty to this function. The function then accesses a JSON file with a list of available specialties and it generates a list from there. If the list element matches the entered specialty, then "True" is returned, otherwise "False".

Not only in .NET, but in the algorithm as a whole, is it possible to properly define the return of function values ​​by code paths? (judging by the compiler message):
'"Program.isProf(string)": не все пути к коду возвращают значение. [writecurrentdata]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
yuopi, 2020-09-16
@seregazolotaryow64

After the loop, you need to write
return false;
because if there is a situation that the program does not get into the cycle, then xs what to return.
In general, the algorithm is also not correct - your loop will stop after the first check.
The method can be rewritten like this:

public static bool isProf(string special)
        {
            dynamic sl = JObject.Parse(File.ReadAllText(@"..\..\..\..\data\source\specialization.json"));

            foreach (var property in sl.specialization)
            {
                if (property == special)
                {
                    return true;
                }
            }
            return false;
        }

Or maybe so?
public static bool isProf(string special)
        {
            var sl = JObject.Parse(File.ReadAllText(@"..\..\..\..\data\source\specialization.json"));
            return sl.specialization.Any(e => e == special);         
        }

upd: It's even better to put the sl field into a class, and not read the file every time, but simply access the field.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question