Using static statement in C# 6.0
The using static is another neat little feature introduced in C# 6.0 which helps you to make your code more readable as well as helps to avoid some redundancy in your code.
We all know that we can import a namespace with using which helps us to use the type name without using the fully qualified name. For example, in most of the programs the first statement will be using System and if we want to call the WriteLine method using the statement given below,
using System;
public class Program
{
public static void Main()
{
Console.WriteLine("This is a test");
}
}
Suppose if we didn't imported the namepsace then, instead of Console.WriteLine() we need to call the method with the fully qualified name. ie System.Console.WriteLine()
public class Program
{
public static void Main()
{
System.Console.WriteLine("This is a test");
}
}
Imagine a class with a large number of calls to the WriteLine method and we will be having a lot of redundant
code for the owner class, in this case System.
Let's take the below code as an example
Here in the class I'm calling Console.WriteLine method 6 times and the methods in the Utils class also 3 times. So with the help of using static statement I will be able import static classes there by avoiding the prefixes for the method names
Syntax
using static <type name>
The using statement can import static members of any type be it a class or struct or enum
So the code given above can be rewritten as
Notice the first two lines in the program and you can see that instead of using, I am using the using static statement to import the static methods in the Console class in the System namespance and the Utils class which is defined in the Common namespace in the program. With this we can now directly call the method names without the type name and our code now looks cleaner and leaner.
No Comments
Connecting Azure Blob Storage account using Managed Identity
Posted 12/9/2022Securing Azure KeyVault connections using Managed Identity
Posted 11/26/2022Manage application settings with Azure KeyVault
Posted 11/9/2022Adding Serilog to Azure Functions created using .NET 5
Posted 4/3/2021Learn how to split log data into different tables using Serilog in ASP.NET Core
Posted 4/23/2020