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

Asked

Viewed 292 times

13

In a question I asked about C#, @Maniero answered me and put an example 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 realized that at the beginning of the code there is a using static.

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

But I realized that in the example above, @Maniero used using static System.Console to call the function WriteLine without having to put Console.WriteLine on the entire call.

What is the difference between using and the using static?

The using does not work for classes? Only for namespace?

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

  • 1

    Other negative? Is there something wrong with my question?

  • 1

    They seem to forget to answer the question, it costs nothing.

1 answer

12


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

The using alone matters namespaces and makes available all types declared on 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);
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Without this artifice:

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

There are situations worth using, other not so much. You also have to think about consistency. If you abuse it can affect readability. There’s a case where it gets a little weird.

Note that it is also possible to import static parts of types that are not static. But members of instances, for obvious reasons, cannot be imported statically, are only accessed by their instance.

  • 1

    Like, version 6 then made things easier.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.