Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# Function Overloading in the New .NET 6 Console Template is Not Working

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading