Search code examples
c#usingc#-6.0using-statementusing-directives

"using static" throwing error


I'm trying to use using static System.Console; rather than using System; so I only have to type out WriteLine("bla") vs Console.WriteLine("bla").

My code is as follows:

using static System.Console;

public class Program
{
    public static void Main()
    {
        WriteLine("this is text")
    }
}

It throws the following errors:

  • Compilation error (line 1, col 7): Identifier expected; 'static' is a keyword

  • Compilation error (line 1, col 14): Expected class, delegate, enum, interface, or struct

However, when I use using System; and Console.WriteLine("this is text"), it works perfectly.

If anyone could explain what's wrong with my code, that would be great, but please explain thoroughly because I know very little about programming :S


Solution

  • In C# 7.0 / VS2017, the code should work, except for the error on line 7 - it's missing a terminating semicolon.

    The following code compiles and runs, and displays:

    this is text

    using static System.Console;
    
    public class Program
    {
        public static void Main()
        {
            WriteLine("this is text");
        }
    }