Introduction
In this article, we are going to discuss how to use the "global using" directive with the "static" modifier.
I assume that you are aware of the “using” and “global using” directives in C# 10. If not, then please read the “global using in C# 10” article first and then resume on this article to get a better understanding.
We will start with the “static” modifier and then learn how to combine the “global” modifier and “static” modifier with a simple example.
Static Modifier
Using Static Modifier was introduced in C# 6.0. This using static directive helps us to use static member and nested types without specifying type names.
Syntax of using static directive is
using static <fully-qualified-type-name>;
fully-qualified-type-name - The <fully-qualified-type-name> is the name of the type whose static members and nested types can be referenced without specifying a type name.
Let’s try to understand this using the below use case,
USECASE
Below code is written without “using static” directive
namespace staticdemo
{
public class staticdemocls
{
public void PrintNames()
{
Console.WriteLine("Kirtesh Shah");
Console.WriteLine("Sweta Shah");
Console.WriteLine("Nitya Shah");
Console.WriteLine("Dilip Shah");
Console.WriteLine("Hansa Shah");
}
public void PrintMathSample()
{
Console.WriteLine(System.Math.Max(500, 50));
Console.WriteLine(System.Math.Min(500,50));
Console.WriteLine(System.Math.Round(500.50));)
}
}
}
In the above example,
- We have created a class with 2 methods
- “Print Names() “ Method prints name on the screen.
- “PrintMathSample()” method prints some numbers after doing some calculations using the “System.Math” namespace.
You might notice that we have used the “Console.WriteLine()” method from “System” Namespace and “Max”, “Min”, and “Round” methods from “System.Math” namespace are used multiple times in the above code.
Let’s execute this code,
staticdemocls staticdemoclsobj = new staticdemocls();
staticdemoclsobj.PrintNames();
staticdemoclsobj.PrintMathSample();


JayavarapuPosted Jan 4, 2024, 6:20 AM
Like this.