By utilizing the C# static directive, we can conveniently access static elements (such as methods and fields) of a class without the necessity of specifying the class name repetitively. Without employing the static directive, it is imperative to utilize the class name every time we wish to invoke static members.
It enables the inclusion of static members from a class into the source file using the following syntax.
C# using static directive syntax
using static <fully-qualified-type-name>
In this instance, the static directive is omitted. It is evident that to invoke a static method from the Math class, the class name is utilized.
C# Example without using static directive
using System;
namespace CSharpFeatures
{
class StaticImport
{
public static void Main(string[] args)
{
double sqrt = Math.Sqrt(144); // Math class is used to access Sqrt() method
string newStr = String.Concat("Hello World",".com");
Console.WriteLine(sqrt);
Console.WriteLine(newStr);
}
}
}
Output
12
hello world.com
In this instance, the static directive is being utilized in the source file, eliminating the need for the class name to precede the method call.
C# Example with using static directive
using System;
using static System.Math; // static directive
using static System.String;
namespace CSharpFeatures
{
class StaticImport
{
public static void Main(string[] args)
{
double sqrt = Sqrt(144); // Calling without class name
string newStr = Concat("Hello World",".com");
Console.WriteLine(sqrt);
Console.WriteLine(newStr);
}
}
}
It remains unchanged, generating identical output even when the function call does not include the type.
Output
12
hello world.com