B.Allen B.Allen - 1 month ago 32
C# Question

issue with "no argument given that corresponds to the required formal parameter"

So this is my code

static void Main(string[] args)
{
Program.AgeAndLabel();
}

public static string AgeAndLabel(string userAge)
{
Console.WriteLine("Enter your age.");
int ageValue = int.Parse(Console.ReadLine());

if (ageValue < 18)
userAge = "Minor";
else
userAge = "Adult";

return userAge;
}


For Program.AgeAndLabel, I am getting the error "There is no argument given that corresponds to the required formal parameter'userAge' of 'Program.AgeAndLabel(string)'" and I don't understand why. I am new to this website and coding in general so if you have any constructive criticism let me know.

jpw jpw
Answer

Remove the string userAge from the function arguments and add it inside function instead; that is where it is needed. The issue is that the variable does not exist inside the function scope where you assign to it.

Also, you are calling the function without arguments, which implies you meant the function to have no arguments.

Your function should probably look something like this:

public static string AgeAndLabel()
{
    string userAge;
    Console.WriteLine("Enter your age.");
    int ageValue = int.Parse(Console.ReadLine());

    if (ageValue < 18)
        userAge = "Minor";
    else
        userAge = "Adult";    
    return userAge;
}

If you had used the ternary operator the last five lines could have been reduced to this instead:

return (ageValue < 18) ? "Minor" : "Adult";

but it's just another (shorter) way of expressing the same thing. (Although less code (usually) means less risk of errors)