Using Static Directive - C# Tutorial
C# Course / Version Features / Using Static Directive

Using Static Directive

BLUF: Mastering Using Static Directive is essential for building robust applications with the .NET ecosystem. This tutorial provides clear explanations and practical examples to help you understand and apply this C# concept.
Enterprise Development Tip: Using Static Directive

C# is a powerful, modern language for enterprise solutions. Discover how Using Static Directive enhances your development workflow in the guide below.

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

Example

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

Example

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

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

Example

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

Output

12
hello world.com

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience