What is the difference between "using" and "using static"?

9

In a question I asked about C #, @bigown answered me and put a sample code in DotNetFiddle.

The code is this:

using static System.Console;

public class Program {
    public static void Main() {
        var objects = new [] {
            new {Id = 2, Nome = "Wallace"},
            new {Id = 4, Nome = "Cigano"}
        };
        WriteLine(objects.GetType());
        foreach (var user in objects) {
            WriteLine($"Meu id é {user.Id}");
            WriteLine($"Meu nome é {user.Nome}");
        }
    }
}

I noticed that at the beginning of the code there is using static .

From what I had learned so far from C #, I knew that to make it easier to use a class that is within a specific namespace , I should use using .

But I noticed that in the example above, @bigown used using static System.Console to call the WriteLine function without having to put Console.WriteLine on the whole call.

What is the difference between using and using static ?

Does using not work for classes? Only for namespace ?

What is the purpose of using static in the specific case?

    
asked by anonymous 16.06.2016 / 18:42

1 answer

9

This is possible from C # 6. You can use using static . to import static classes, so all your public members are available for direct use without the class qualifier.

The using only imports namespaces and makes available all types declared in it.

using static System.Console;
using static System.Math;
using static System.Convert;
using static System.DateTime;

public class Program {
    public static void Main() {
        WriteLine(Round(ToDouble("123.45")));
        WriteLine(Now);
    }
}

See example in dotNetFidlle and in CodingGround .

Without this artifice:

using System;

public class Program {
    public static void Main() {
        Console.WriteLine(Math.Round(Convert.ToDouble("123.45")));
        Console.WriteLine(DateTime.Now);
    }
}

It has situations that it pays to use, another not so much. You also have to think about consistency. Abusing can affect legibility. There is a case where it's kind of weird.

Note that you can also import static parts of types that are not static. But instance members, for obvious reasons, can not be imported statically, are only accessed by their instance.

    
16.06.2016 / 18:48