Reputation: 13
In the following code, I am trying to override the calculate
method, but I am getting the following error. What am I doing wrong?
A local or parameter named "calculate" cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
using System;
namespace Assignment_7_George
{
class RandomNumbers
{
static void Main(string[] args)
{
// initialize variables
int sumofrandom = 0;
double average = 0;
double total = 0;
// create random number object
Random randomNumbers = new Random();
//for loop that repeats twenty times to find a random number between 1 - 100
for (int i = 0; i < 20; i++)
{
//find random number method
int getRandom()
{
int random = 1 + randomNumbers.Next(1,101);
sumofrandom = sumofrandom + random;
return sumofrandom;
}
getRandom();
}
// calculate average
double calculate(double sumofrandom, ref double average, int count)
{
int x = 20;
Convert.ToDouble(x);
average = sumofrandom / x;
Convert.ToInt32(average);
return average;
}
// call method
calculate(sumofrandom, ref average, 20);
Console.WriteLine("The average of the 20 random numbers is " + Convert.ToInt32(average) + ".");
Console.WriteLine(" ");
//loop repeats 5 times
for (int i = 0; i < 5; i++)
{
Console.Write("Enter a double value ");
double input = Convert.ToDouble(Console.ReadLine());
// cal method adds input to total
double calculate(double input, ref double total)
{
total = total + input;
return total;
}
// call method
calculate(input, ref total);
// prints results
if (i > 3)
{
Console.WriteLine("The total is " + calculate(input, ref total));
break;
}
}
}
}
}
Upvotes: 0
Views: 186
Reputation: 100620
Method overloading does not work for local functions. The code is using local functions and they follow regular rules for defining variables in a scope - you can't redefine it if parent scope already contains something with the same name (see Variable scope confusion in C#). Note that only name of the local method is taken into account for that check unlike class level methods that use both name and parameters to find matching function ("method overloading").
You can either
ref
/out
parameters are tricky to get right (Cannot use ref or out parameter in lambda expressions).Upvotes: 2