-1

I tried to use something like using Printer; but it doesn't work.

I just want use P(); instead of Printer.P();

File Printer.cs

using System;

namespace animals
{
    public class Printer
    {
        public static void P()
        {
            P("\a");
        }

        public static void P(object val, bool doEnterAfterLine = true, bool printInOneLine = false)
        {
            P(val.ToString());
            if (doEnterAfterLine)
                Console.WriteLine(); //enter
        }

        static void P(bool printSeparator = false)
        {
            if (printSeparator == false)
                return;

            P("---------------------------------------------------------", true);
        }


        static void P(string value = "none", bool modifyColor = false, bool ding = false, bool printInOneLine = false)
        {
            var oldColor = Console.ForegroundColor;

            if (modifyColor)
                Console.ForegroundColor = ConsoleColor.Magenta;

            if (printInOneLine)
                Console.Write(value + " ");
            else
                Console.WriteLine(value);

            Console.ForegroundColor = oldColor; //recover color

            if (ding)
            {
                Console.Write("\a");
            }
        }
    }
}

File Program.cs

using System;
// this resolve problem: using static animals.Printer;
 
namespace animals 
{
     class Program
     {
         static void Main(string[] args)
         {           
             Printer.P(); // it works
             P();         // info: does not exist in current context                        
         }
     }
}

Dharman
  • 30,962
  • 25
  • 85
  • 135
yvisek
  • 1
  • 2

1 Answers1

3

Use using static <namespace>.<class>; to access the members of <class> without qualifying its name.

using static animals.Printer;
bg117
  • 354
  • 4
  • 13
  • Mark this answer as correct by clicking the check mark **if it solved your problem** – bg117 Nov 02 '21 at 01:55
  • 1
    using static animals.Printer; --> work great! Thank you! – yvisek Nov 02 '21 at 02:03
  • 1
    Probably worth adding that I haven't ever seen this used in production code, most likely because it breaks some foundational assumptions about method calls and therefore can cause more problems than the few characters it saves. – Luke Briggs Nov 02 '21 at 02:05
  • @LukeBriggs I mean, WPF itself has methods like `FindResource()` which you invoke without qualifying its name. – Hans GD Aug 17 '23 at 15:11