I am getting errors trying to overload the function Print(object)
in the new .NET 6 C# console app template (top-level statements).
void Print(object obj) => Print(obj, ConsoleColor.White);
void Print(object obj, ConsoleColor color)
{
Console.ForegroundColor = color;
Console.WriteLine(obj);
Console.ResetColor();
}
Errors are:
- From
Print(obj, ConsoleColor.White)
->No overload for method Print() that takes 2 arguments
- From
Print(object obj, ConsoleColor color)
->A local variable or function named 'Print' is already defined in this scope
I tried to switch their order but it still throws errors. What's going on?
CodePudding user response:
Contents of top-level is assumed to be an internals of Main
, so you declared two local functions inside Main
. And local functions does not support overloading.
You can:
switch to the old style template with full specification of class
class Program { static void Main(){} void Print(object obj) => Print(obj, ConsoleColor.White); void Print(object obj, ConsoleColor color) { Console.ForegroundColor = color; Console.WriteLine(obj); Console.ResetColor(); } }
to stay with new template, but wrap your function into the separate class
var c = new C(); c.Print("test"); public class C{ public void Print(object obj) => Print(obj, ConsoleColor.White); void Print(object obj, ConsoleColor color) { Console.ForegroundColor = color; Console.WriteLine(obj); Console.ResetColor(); }
}
Related github isse with some technical details: https://github.com/dotnet/docs/issues/28231