While writing my blog post yesterday about class aliases, I was reading through the documentation about the using keyword and noticed another feature I almost forgot: ‘using static’.
Through ‘using static’ you can import static members of types directly into the current scope. This can safe you from some extra typing work if you need a specific static class over and over again.
An example:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
class Program | |
{ | |
static void Main() | |
{ | |
Console.WriteLine("Hello world!"); | |
Console.WriteLine("Another message"); | |
Console.ReadKey(); | |
} | |
} |
In the code above I have to repeat the ‘Console’ static class for each call. Now let’s rewrite this example with the help of ‘using static’:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using static System.Console; | |
class Program | |
{ | |
static void Main() | |
{ | |
WriteLine("Hello world!"); | |
WriteLine("Another message"); | |
ReadKey(); | |
} | |
} |
More information: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-directive#static-modifier